不确定如何准确表达我的问题,但我本质上想循环遍历列表并仅显示前 4 个匹配项。
{% for reward_type in reward_types %}
<h2>{{ reward_type.name }}</h2>
<div class="reward_category">
{% for category in reward_categories %}
{% if category.reward_type == reward_type %}
.
.
Show the first 4 matches
.
.
{% endif %}
{% endfor %}
</div>
{% endfor %}
最佳答案
您可以使用slice
如果没有{% ifcategory.reward_type ==reward_type %}
。
即如果您有 category_matching_rewards
,它是具有 category.reward_type ==reward_type
的列表,那么在模板中可以这样做
{%for category in category_matching_rewards|slice:"4" %}
Show catgory
....
{%endfor%}
关于Django 模板 for 循环并显示前 X 个匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12473888/