Dingo
Dingo

Reputation: 113

Comparing corresponding elements of two lists in Django Template

I have two lists of equal sizes like so:

change_list = ['none', 'M', 'D', 'none]

print_list = ['examples', 'app.py', 'list.fr', 'template']

I pass them through the view and I need to know what the value is on the first list so I can display the elements of the second one with a different color according to what's on the first list. For example, I need to display 'app.py' as orange in the template due to the 'M' in the first list.

I've searched around and I have no idea how to do this. I tried to pass the len of the list as a range to the view like this:

{% for i in len%}
    {% if changes_list.i == "M" %}
        <p style="color:orange;"> {{print_list.i}}</p>
    {% endif %}
{% endfor %}

But it didn't work.

I'm not sure if I formulated the question correctly but I wasn't exactly sure how to explain this.

Thank you in advance.

Upvotes: 0

Views: 1000

Answers (2)

Anthony
Anthony

Reputation: 959

Your syntax is off

Here's a simple solution:

We loop through the list and check if the i is equal to "M"

{% for i in change_list %}
    {% if i == "M" %}
       <p>I</p>
    {% else %}
        <p>I Not == M</p>
    {% endif %}
{% endfor %}

If you wanted to compare the two lists:

{% for i in change_list %}
    {% for x in print_list %}
      {% if i == x %}
       <p>I</p>
      {% else %}
        <p>I Not == X</p>
      {% endif %}
  {% endfor %}
{% endfor %}

Upvotes: 1

Niko B
Niko B

Reputation: 841

I would give a shot like below. Warning, untested code ;)

In your view :

change_list = ['none', 'M', 'D', 'none']
print_list = ['examples', 'app.py', 'list.fr', 'template']
template_list = list(zip(change_list, print_list))

And you just pass template_list to your template.

In your template :

{% for i in template_list%}
    {% if i.0 == "M" %}
        <p style="color:orange;"> {{i.1}}</p>
    {% endif %}
{% endfor %}

And you should be good.

Please note that in the view I use list() aroud zip() because I do not know if a zip object would work in a Django template. Feel free to test without it.

Upvotes: 1

Related Questions