【问题标题】:Django: Accessing for loop variable in the child templateDjango:访问子模板中的循环变量
【发布时间】:2016-11-03 05:38:51
【问题描述】:

我有一个基本模板:

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%}

然而,孩子似乎无法看到变量“object”。我知道它是 for 循环的局部变量,但我怎样才能让它对孩子可见?

【问题讨论】:

  • 因为循环中有其他东西我没有写在这里,在许多模板之间重复。
  • 你可以考虑为此写一个上下文处理器

标签: django python-2.7 django-templates


【解决方案1】:

我想通了。我必须先保存循环变量才能将其传递给孩子:

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%}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-07
    • 2018-11-17
    • 1970-01-01
    • 2014-04-08
    • 2018-07-01
    • 2012-01-24
    • 2017-08-29
    • 2021-07-31
    相关资源
    最近更新 更多