{% for each_item in item.artifacts %}
{% if each_item.scanner_count > 0 and each_item.scanner_match > 0 %}
{% if forloop.counter <= 5 %}
<tr>
<td>{{each_item.threat_name}}</td>
</tr>
{% else %}
{% if forloop.last %}
<p><b><i> {{ forloop.counter|add:"-5" }} rows were truncated. See full report for more details. </i></b></p>
{% endif %}
{% endif %}
{% else forloop.counter -=1 %}
{% endif %}
{% endfor %}
错误:第 171 行的模板标记格式不正确:"else forloop.counter -=1" 我想仅在条件成功时增加计数器。不知道如何使用forloop.counter来做到这一点。目标是打印 5 行有效输出(扫描仪计数>0 和扫描仪匹配>0(
您可以使用add
和forloop计数器的组合来实现您想要实现的目标。 但请记住,您需要传递一些变量(我在这里使用了rank
来将增量变量存储在模板中。
views.py
rank = 0
return render(request, "base.html", {"items": items, "rank": rank})
.html
{% for each_item in items %}
{% if each_item.scanner_count > 0 and each_item.scanner_match > 0 %}
{% if forloop.counter|add:rank <= 5 %}
<tr><td>{{each_item.threat_name}}</td></tr>
<br>
{% else %}
{% if forloop.last %}
<p><b><i> {{ forloop.counter|add:"-5" }} rows were truncated. See full report for more details. </i></b></p>
{% endif %}
{% endif %}
{% endif %}
{% endfor %}
正如其他评论者所指出的,您不能在模板中分配forloop.counter
,因为这将被视为应该在视图(控制器(中的逻辑。从您的代码中删除{% else forloop.counter -= 1 %}
,它应该按照我认为您的意图工作。如果没有,要么在传递给模板的对象(上下文(中添加逻辑,要么使用其他 forloop 属性/变量,如 Django 文档中的 https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#for