[Django]-Check for presence in a list django template

102πŸ‘

βœ…

I don’t think that you can define a list directly in the template. You could pass a list to the template and do

{% if value in my_list %}

For example:

{% if name in 'foo,bar' %}
    bla
{% endif %}

Alternatively, you could write a template tag which takes parameters like this:

{% ifinlist value "val1,val2,val3" %}
πŸ‘€schneck

25πŸ‘

You could write the if condition as

{% if value in 'Pass,Fail' %}

No need of template tag or list from backend

πŸ‘€nandhini ks

12πŸ‘

Django Template:

{% value|ifinlist:"val1,val2,val3" %}

Template Tag:

from django import template

register = template.Library()

@register.filter(name='ifinlist')
def ifinlist(value, list):
    return value in list
πŸ‘€Sadia Arif

2πŸ‘

How to pass a list to your template? I personaly use extra_context attribute in generic views like this:


class MyObjectDetailView(DetailView):
    model = MyObject
    template_name = "path/to/object_detail.html"
    extra_context = {'DISABLED': [model.ACCEPTED, model.REFUSED]}

Then in my template, for example, to disable btn:


<input class="btn"{% if object.status in DISABLED %} disabled="disabled"{% endif %}">

πŸ‘€Emilio Conte

Leave a comment