Django 模板中用于循环的条件计数器

时间:2021-02-03 11:21:20

标签: python html django for-loop django-templates

我希望我的 for 循环在满足三次 if 条件后结束,同时在我的电子商务网站中呈现我的“产品”详细信息。

category.html

    {% for item in subcategory %}
    {% with counter="0" %}
    <div>
        <h5 class="my-0" style="font-weight: 700;">{{ item.title }}</h3>
    </div>
    <div class="row">
        {% for i in products %}
        {% if i.category.id == item.id %}
        {{ counter|add:"1" }}
        {% if counter == "3" %}
            {{ break}}
        {% endif %}
        <div class="col-3 p-0 px-1 my-3">
            <a href="{% url 'product_detail' i.id i.slug %}">
                <img class="w-100" id="catbox" src="{{ i.image.url }}" alt="">
            </a>
        </div>
        {% endif %}
        {% endfor %}
        <div class="col-3 p-0 my-3   text-center"
            style="border-radius: 10px;background: url({% static 'images/temp.jpeg' %}); background-size: cover;">
            <div class="h-100 w-100 m-0 p-0" style="background: rgba(0, 0, 0, 0.61);border-radius: 10px;">
                <div style="position: relative;top: 50%;transform: translateY(-50%);">
                    <a href="{% url 'category_product' item.id item.slug %}" class="text-white " href="#"><strong>SEE
                            ALL</strong></a>
                </div>
            </div>
        </div>
    </div>
    {% endwith %}
    {% endfor %}

我希望第二个 for 循环,即 {% for i in products %} 中断一次 if 条件,即其中的 {% if i.category.id == item.id %} 满足三次。但是我设置为 0 的计数器会反复增加到 1,而不是通过 for 循环反复增加。因为里面有一个 if 条件,所以我也不能使用 forloop.counter 。 我希望对第一个 for 循环的每次迭代重复此过程,即 {% for item in subcategory %}

2 个答案:

答案 0 :(得分:1)

不存在用于中断(或像 Python 中的继续)目的的模板标记。发送未经处理的数据并在模板中工作通常是一种不好的做法。我认为首先您需要根据视图中的条件制作一个列表,然后将其传递给模板以使用它们。 但是,您可以做一件事(据我说非常低效),

{% if counter <= 3 %}
   do the job which you meant to do before breaking
{% endif %}

或者您可以尝试创建自己的模板标签/过滤器。但我建议您在模板中保持简单,并在视图中将其弄乱。 view docs for template tags

答案 1 :(得分:0)

您不需要自己定义计数器并使用 'with' 标签。您可以使用 django 内置计数器进行循环。您可以像这样在 for 循环中访问计数器:{{ forloop.counter }} 从 1 开始,{{ forloop.counter0 }} 从 0 开始。您也可以像这样访问外部 for 循环计数器的计数器:{ {1}} 检查 here

相关问题