返回的每个项目的 Django 阅读索引
Django reading index of each item returned
我正在 return 在模板的标准 for 循环中生成项目列表。是否可以获得每个项目的索引值 returned.
{% for entry in latest_entries %}
<li class="list-item">
<button class="button button-circle"><span class="list-index">1</span></button>
<a class="SidebarLatestTitle" href="{{ entry.get_absolute_url }}">{{ entry.title }}</a>
</li>
{% endfor %}
我希望将按钮中的硬编码“1”return 设为列表中的正确数字。如果 returned 了 10 个结果,则 (1-10)。 Django 是否提供访问此号码的方法?
听起来你在问 forloop.counter
:
forloop.counter
- The current iteration of the loop (1-indexed)
{% for entry in latest_entries %}
<li class="list-item">
<button class="button button-circle"><span class="list-index">{{ forloop.counter }}</span></button>
<a class="SidebarLatestTitle" href="{{ entry.get_absolute_url }}">{{ entry.title }}</a>
</li>
{% endfor %}
https://docs.djangoproject.com/en/1.7/ref/templates/builtins/#for
使用神奇的forloop.counter
或forloop.counter0
我正在 return 在模板的标准 for 循环中生成项目列表。是否可以获得每个项目的索引值 returned.
{% for entry in latest_entries %}
<li class="list-item">
<button class="button button-circle"><span class="list-index">1</span></button>
<a class="SidebarLatestTitle" href="{{ entry.get_absolute_url }}">{{ entry.title }}</a>
</li>
{% endfor %}
我希望将按钮中的硬编码“1”return 设为列表中的正确数字。如果 returned 了 10 个结果,则 (1-10)。 Django 是否提供访问此号码的方法?
听起来你在问 forloop.counter
:
forloop.counter
- The current iteration of the loop (1-indexed)
{% for entry in latest_entries %}
<li class="list-item">
<button class="button button-circle"><span class="list-index">{{ forloop.counter }}</span></button>
<a class="SidebarLatestTitle" href="{{ entry.get_absolute_url }}">{{ entry.title }}</a>
</li>
{% endfor %}
https://docs.djangoproject.com/en/1.7/ref/templates/builtins/#for
使用神奇的forloop.counter
或forloop.counter0