24

was wondering if there is a way to test if a variable is inside of a list or dict in django using the built in tags and filters.

Ie: {% if var|in:the_list %}

I don't see it in the docs, and will attempt something custom if not, but I don't want to do something that has already been done.

Thanks

3 Answers 3

41

In Django 1.2, you can just do

{% if var in the_list %}

as you would in Python.

Otherwise yes, you will need a custom filter - it's a three-liner though:

@register.filter
def is_in(var, obj):
    return var in obj
Sign up to request clarification or add additional context in comments.

4 Comments

can the list be in the template like: {% if var in ['item1','item2','item3'] %}
@Sevenearths I just tried it and can confirm that, as of Django 1.5.1, the list cannot be defined in the if statement like that.
how would we go about doing it then?
@laycat: we must compare with a list variable given inside the context. btw: how to avoid Django Template Language completely??
6

Want to pass a comma separated string from the template? Create a custom templatetag:

from django import template
register = template.Library()

@register.filter
def in_list(value, the_list):
    value = str(value)
    return value in the_list.split(',')

You can then call it like this:

{% if 'a'|in_list:'a,b,c,d,1,2,3' %}Yah!{% endif %}

It also works with variables:

{% if variable|in_list:'a,b,c,d,1,2,3' %}Yah!{% endif %}

Comments

-3

In Django 3... It's simply by:

someHtmlPage.html

<html>
    {%if v.0%}
        <p>My string {{v}}</p>
    {%else%}
        <p>My another typy {{v}}</p>
    {%endif%}
</html>

1 Comment

This answer does not answer the question. In the example of your answer you are accessing a position in an array, not all positions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.