Django 模板 for 循环并显示前 X 个匹配项

标签 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 %}

最佳答案

您可以使用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/

相关文章:

c++ - const ref 传递的模板化参数是否优化为在足够小时按值传递?

c++ - 如何在模板类中重载 less 运算符以供排序算法使用?

python - Django 模型。在多个模型类和管理中关联元组

javascript - 使用 Django 将 JSON 转为 JS : SyntaxError: missing : after property id

python - Django 框架是否容易受到本地文件包含(LFI)和远程文件包含(RFI)的影响?

javascript - JSON 在我的 JavaScript 中被全局修改...为什么?

c++ - 在函数参数化的模板中推导参数类型

c++ - 如何仅使用标准库确定强类型的基类型是否为 std::array<char, N>

json - 类型错误 : <object> is not JSON serializable

python - 带有 filter() 和 order_by() 的查询集 distinct() 不起作用