这是django模板中的一个错误:forloop.parentloop.first还是我误解了?

时间:2012-05-23 04:59:18

标签: django django-templates

from django.template import Template, Context
template = Template("""
      {% for language in languages %}
        THIS IS forloop.parentloop.first +++++++++
        {% for tag in revision_tags %}
          {% for case in CASES %}
          <tr>
            {% if forloop.parentloop.first %}<th rowspan="6">{{ language|capfirst }}</th>{% endif %}
            {% if forloop.first %}<th rowspan="2">{{ tag }}</th>{% endif %}
            <th>{{ case|capfirst }}</th>
          </tr>
          {% endfor %}
        {% endfor %}
      {% endfor %}
""")

c = Context({
    'languages': ["english", "french"],
    'revision_tags': ["d", "s", "p"],
    'CASES': ["foo", "bar"],
})

h = template.render(c)
print h

我希望每种语言只看一次,但我会两次。

2 个答案:

答案 0 :(得分:0)

试试这个(未经测试)......

{% for language in languages %}
    THIS IS forloop.parentloop.first +++++++++
    {% for tag in revision_tags %}
      {% if forloop.parentloop.first %}<th rowspan="6">{{ language|capfirst }}</th>{% endif %}
      {% for case in CASES %}
      <tr>
        {% if forloop.first %}<th rowspan="2">{{ tag }}</th>{% endif %}
        <th>{{ case|capfirst }}</th>
      </tr>
      {% endfor %}
    {% endfor %}
  {% endfor %}

答案 1 :(得分:0)

这不是一个错误,我误解了。测试应为{% if forloop.parentloop.first and forloop.first %},以便在每次父母迭代时获得1,在这种情况下为language

  {% for language in languages %}
    {% for tag in revision_tags %}
      {% for case in CASES %}
      <tr>
        {% if forloop.parentloop.first and forloop.first %}
        <th rowspan="6">{{ language|capfirst }}</th>
        {% endif %}
        {% if forloop.first %}<th rowspan="2">{{ tag }}</th>{% endif %}
        <th>{{ case|capfirst }}</th>
      </tr>
      {% endfor %}
    {% endfor %}
  {% endfor %}