Home > front end >  Django: Count forloop.first only if a second if condition is met
Django: Count forloop.first only if a second if condition is met

Time:02-04

I have the following (oversimplified example):

{% for item in myitems  %}
  {% if item == "orange" %}
    {{item}}
  {% endif %}
{% endfor %}

Let's say that my list myitems is ['apple','orange','watermelon','orange']. The above code prints twice "orange". But I don't want this... I would like to print it once. So then I tried using if forloop.first

{% for item in myitems  %}
  {% if item == "orange" %}
    {% if forloop.first %}
     {{item}}
    {% endif %}
  {% endif %}
{% endfor %}

The first loop will be item=apple so it won't print the item because it is not "orange". In the second loop now we have item=orange but it no longer fulfills if forloop.first as it is the second loop already so it won't print the item. How can I print orange once? Is there a statement such us: if forloop.first (start numbering from the first print)

CodePudding user response:

I think you can print the element of myitems only once when condition is met using a variable in the template and changing its value when the condition is met:

{% set stop_loop="" %}

{% for item in myitems  %}
    {% if stop_loop %}
    {% elif item == "orange" %}
        {{item}}
        {% set stop_loop="true" %}
    {% endif %}
{% endfor %}

IMO, this kind of business logics should be in the view rather than template.

CodePudding user response:

If I've correctly understood, you're basically looking for this piece of code:

{% for item in myitems  %}
    {% if item == "orange" and forloop.first %}
        {{item}}
    {% endif %}
{% endfor %}

A simple and should do the job. With the example you provided ['apple','orange','watermelon'], the rendered template would be blank.

CodePudding user response:

This is my solution based on previous comments

{% with False as stop_loop %}
{% for item in myitems  %}
    {% if stop_loop %}
    {% elif item == "orange" %}
        {{item}}
        {% update_variable True as stop_loop %}
    {% endif %}
{% endfor %}
{% endwith %}

And I need to register in templatetags the following:

@register.simple_tag
def update_variable(value):
    return value

It works

  • Related