tej*_*tan 32 django for-loop django-templates
我有这个代码
{% for account in object_list %}
<tr>
{% for field, value in book.get_fields %}
<th>{{ field.verbose_name }}</th>
{% endfor %}
</tr>
{{ break }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
我想在第一次迭代后打破for循环.休息不起作用
小智 93
我认为你应该使用切片来实现你的目标
{% for account in object_list|slice:":1" %}
Run Code Online (Sandbox Code Playgroud)
小智 5
您不能使用 break 语句,但您可以选择不在 html 上打印它们。这不是最佳解决方案,但您可以使用它。我使用以下一个;
{%for tumbnail in image %}
{%if tumbnail.object_id == element.id %}
<img src="/media/{{ tumbnail.image }}" class="tr_all_hover"alt="">
{{ "<!--" }}
{%endif%}
{%endfor%}
{{ "-->" }}
Run Code Online (Sandbox Code Playgroud)
它在浏览器上基本上是这样的。 http://i.stack.imgur.com/MPbR3.jpg
小智 5
{% for i in list %}
{% if forloop.counter < 11 %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ i.product__name }}</td>
<td>{{ i.brand__name }}</td>
<td>{{ i.country__name}}</td>
<td>{{ i.city__name}}</td>
</tr>
{% endif %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)