Django模板用于循环并显示第一个X匹配

sup*_*er9 2 django templates

不确定如何说出我的问题,但我基本上想循环一个列表,只显示前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 %}
Run Code Online (Sandbox Code Playgroud)

Roh*_*han 22

你可以使用,slice如果没有{% if category.reward_type == reward_type %}.

即如果你有category_matching_rewards哪个是列表category.reward_type == reward_type然后在模板中,它可以作为

{%for category in category_matching_rewards|slice:"4" %}
       Show catgory
       ....
{%endfor%}
Run Code Online (Sandbox Code Playgroud)