扩展Django模板并覆盖循环中的块

时间:2014-03-31 05:08:30

标签: django templates

修改

因此,如果您将extends标记移动到comment标记上方,则可以使用下面的示例。根据{{​​3}}:"如果您在模板中使用{%extends%},则它必须是该模板中的第一个模板标记。否则,模板继承将不起作用。"

原始问题:

我还是刚接触Django,所以我做了一些谷歌搜索,但却找不到任何有帮助的东西。如果这是重复的话,请道歉!

方案

让我们说我有许多不同的模型共享同一个超类,我想在部分显示所有常见字段:

    {% comment %}
        Template: 
            _model_attribute_list.html
        Args:
            models: A collection of models that inherit from the same superclass
    {% endcomment %}

    {% for model in models %}
      <ul>
        <li>Common Attribute 1: {{ model.common_attribute_1 }}</li>
        <li>Common Attribute 2: {{ model.common_attribute_2 }}</li>
        <li>Common Attribute 3: {{ model.common_attribute_3 }}</li>
      </ul>
    {% endfor %}

够容易。现在,我有兴趣不仅展示那些属性,还展示特定于特定模型的属性。我没有复制那部分N次,而是想添加块:

    {% comment %}
        Template: 
            _model_attribute_list.html (with blocks added)
        Args:
            models: A collection of models that inherit from the same superclass
    {% endcomment %}

    {% for model in models %}
      <ul>
        {% block leading_attributes %}{% endblock %}
        <li>Common Attribute 1: {{ model.common_attribute_1 }}</li>
        <li>Common Attribute 2: {{ model.common_attribute_2 }}</li>
        <li>Common Attribute 3: {{ model.common_attribute_3 }}</li>
        {% block trailing_attributes %}{% endblock %}
      </ul>
    {% endfor %}

并让其他模型特定的部分覆盖它们,以便它们可以包含自定义字段:

    {% comment %}
        Template: 
            _model1_attribute_list.html
        Args:
            models: A collection of Model1
    {% endcomment %}
    {% extends '_model_attribute_list.html' %}

    {% block leading_attributes %}
        <li>Custom Attribute 1: {{ model.custom_attribute_1 }}</li>
        <li>Custom Attribute 2: {{ model.custom_attribute_2 }}</li>
    {% endblock %}

根据Django docs,在扩展模板时:

  

...模板引擎会注意到[父模板]中的...块标签,并将这些块替换为子模板的内容

鉴于文档说的是什么,为什么这不起作用?

我的假设是,当模板引擎呈现模板时,它会在评估循环之前插入块,从而导致错误,因为model.custom_aatribute_N的值尚不存在。

此外,我实际上看不到任何错误,但模板无法呈现。有没有办法让Django在这种情况下吐出错误?

谢谢!

1 个答案:

答案 0 :(得分:1)

我不确定您当前设置的原因是什么,但这是另一种可以尝试的方式。

  • 使用您想要的适当块创建通用模板
  • 根据您的网页创建专门的模板
  • 在页面中,不是扩展模板,而是包含模板。

例如:

base.html文件

  <ul>
    {% block leading_attributes %}{% endblock %}
    <li>Common Attribute 1: {{ model.common_attribute_1 }}</li>
    <li>Common Attribute 2: {{ model.common_attribute_2 }}</li>
    <li>Common Attribute 3: {{ model.common_attribute_3 }}</li>
    {% block trailing_attributes %}{% endblock %}
  </ul>

special1.html

{%extends "base.html" %}
{% block leading_attributes %}
    <li>Custom Attribute 1: {{ model.custom_attribute_1 }}</li>
    <li>Custom Attribute 2: {{ model.custom_attribute_2 }}</li>
{% endblock %}

your_page.html

{% for model in models %}
    {%include "special1.html" %}
{%endfor%}