Ian P
Ian P

Reputation: 1533

Is 'if element in aList' possible with Django templates?

Does something like the python

if "a" in ["a", "b", "c"]:
    pass

exist in Django templates?

If not, is there an easy way to implement it?

Upvotes: 2

Views: 266

Answers (2)

wlashell
wlashell

Reputation: 898

Not directly, there is no if x in iterable template tag included.

This is not typically something needed inside the templates themselves. Without more context about the surrounding problem a good answer cannot be given. We can guess and say that you want to either pass a nested list like the above comment, or you really just need to do more calculation in the view and pass a single list (testing for empty if you don't want it to do anything).

Hope this helps.

Upvotes: 1

S.Lott
S.Lott

Reputation: 391952

This is something you usually do in your view functions.

aList = ["a", "b", "c"]
listAndFlags = [ (item,item in aList) for item in someQuerySet ]

Now you have a simple two-element list that you can display

{% for item, flag in someList %}
    <tr><td class="{{flag}}">{{item}}</td></tr>
{% endfor %}

Upvotes: 2

Related Questions