【问题标题】:Django which template to extends with if blockDjango 使用 if 块扩展哪个模板
【发布时间】:2021-12-12 13:17:09
【问题描述】:

我有两个不同的模板,必须在三个不同的页面中扩展。 有没有用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 %}

【问题讨论】:

    标签: python django django-templates


    【解决方案1】:

    如果您使用模板继承,{% extends … %} [Django-doc] 应该是第一个模板标签。您不能使用{% if … %} 块,根据请求的完整路径检测父级也不是一个好主意。

    您可以在视图中执行此操作,并使用:

    def my_view(request):
        context = { 'parent': 'index.html' }
        return render(request, 'my_template.html', context)

    然后在模板中使用:

    {% extends parent %}
    …

    【讨论】:

    • 如何包含其他模板 base.html?
    • @aba2s:你用不同的上下文渲染它,所以{ 'parent': 'base.html' })。
    • 它工作正常。非常感谢
    猜你喜欢
    • 2010-11-27
    • 1970-01-01
    • 2013-09-15
    • 2012-02-01
    • 1970-01-01
    • 2019-05-22
    • 2012-04-17
    • 2013-06-13
    相关资源
    最近更新 更多