Django 用 if 块扩展哪个模板
Django which template to extends with if block
我有两个不同的模板,必须在三个不同的页面中扩展。
有没有用 if block
扩展模板的解决方案?
我试过了没有成功。
{% if 'project' in request.get_full_path %}
{% extends 'index.html' %}
{% elif 'network' in request.get_full_path %}
{% extends 'base.html' %}
{% elif 'zoneset' in request.get_full_path %}
{% extends 'base.html' %}
{% endif %}
{% load crispy_forms_tags %}
{% block title %} Network {% endblock title %}
{% block content %}
<div class="row">
<div class="col-md">
<div class="card card-body">
<h6>Update</h6>
<form class="" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form|crispy}}
<input type="submit" name="" value="Update">
</form>
</div>
</div>
</div>
{% endblock %}
如果您使用模板继承,{% extends … %}
[Django-doc] 应该是第一个模板标签。您不能使用 {% if … %}
块,根据请求的完整路径检测父级也不是一个好主意。
您可以在视图中执行此操作,并使用:
def my_view(request):
context = { <strong>'parent': 'index.html'</strong> }
return render(request, 'my_template.html', context)
然后在模板中使用:
{% extends <strong>parent</strong> %}
…
我有两个不同的模板,必须在三个不同的页面中扩展。
有没有用 if block
扩展模板的解决方案?
我试过了没有成功。
{% if 'project' in request.get_full_path %}
{% extends 'index.html' %}
{% elif 'network' in request.get_full_path %}
{% extends 'base.html' %}
{% elif 'zoneset' in request.get_full_path %}
{% extends 'base.html' %}
{% endif %}
{% load crispy_forms_tags %}
{% block title %} Network {% endblock title %}
{% block content %}
<div class="row">
<div class="col-md">
<div class="card card-body">
<h6>Update</h6>
<form class="" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form|crispy}}
<input type="submit" name="" value="Update">
</form>
</div>
</div>
</div>
{% endblock %}
如果您使用模板继承,{% extends … %}
[Django-doc] 应该是第一个模板标签。您不能使用 {% if … %}
块,根据请求的完整路径检测父级也不是一个好主意。
您可以在视图中执行此操作,并使用:
def my_view(request):
context = { <strong>'parent': 'index.html'</strong> }
return render(request, 'my_template.html', context)
然后在模板中使用:
{% extends <strong>parent</strong> %}
…