Django:在子模板中访问循环变量

时间:2016-06-30 23:16:23

标签: django python-2.7 django-templates

我有一个基本模板:

base.html:

    {% for object in object_list %}  
            {%block object_attributes%} {%endblock%}
    {% endfor %}

和一个从中继承的孩子:

child.html

{% extends "base.html" %}

{%block object_attributes%} 
          {{block.super}}
          <td>{{ object.name }}</td>
          <td>{{ object.address }}</td>
{%endblock%}
然而,似乎孩子无法看到变量&#34; object&#34;。我理解它是for循环的局部变量,但我怎么能让它对孩子可见?

1 个答案:

答案 0 :(得分:0)

我明白了。我必须首先保存循环变量以将其传递给子:

base.html文件:

{% for object in object_list %}  
            {% with object as object_pass %}  
            {%block object_attributes%} {%endblock%}
            {% endwith %}
{% endfor %}

child.html

{% extends "base.html" %}

{%block object_attributes%} 
      {{block.super}}
      <td>{{ object_pass.name }}</td>
      <td>{{ object_pass.address }}</td>
{%endblock%}