Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django templates: testing if variable is in list or dict

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

like image 815
Paul Avatar asked Jun 25 '10 12:06

Paul


2 Answers

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
like image 148
Daniel Roseman Avatar answered Nov 19 '22 14:11

Daniel Roseman


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 %}
like image 5
dotcomly Avatar answered Nov 19 '22 15:11

dotcomly