Deepend
Deepend

Reputation: 4155

Django: if in list template tag

Is it possible to write a template tag that will check the contents of a list?

Currently I have the below checking from 5 to 13, but this is very verbose and I will need to do this nine times.

{% if wizard.steps.current == '5' %}                    
    <img src="{% static "survey/images/pathtwo/" %}{{display_image}}"/>                                                                     
    <section>   
    <span class="tooltip"></span>   
    <div id="slider"></div>  
    <span class="volume"></span>  
    </section>      
{% endif %}
{% if wizard.steps.current == '6' %}            
    <img src="{% static "survey/images/pathtwo/" %}{{display_image}}"/>                                                                     
    <section>   
    <span class="tooltip"></span>   
    <div id="slider"></div>  
    <span class="volume"></span>  
    </section>      
{% endif %}
    ...
    ...

I have tried

{% if wizard.steps.current in ['5','6','7','8','9','10','11','12','13'] %}              
    <img src="{% static "survey/images/paththree/" %}{{display_image}}" />                                                                      
    <section>   
    <span class="tooltip"></span>   
    <div id="slider"></div>  
    <span class="volume"></span>  
    </section>      
{% endif %} 

But get an error

Exception Value: Could not parse the remainder: '['5','6','7','8','9','10','11','12','13']' from '['5','6','7','8','9','10','11','12','13']'

Any ideas?

Upvotes: 3

Views: 909

Answers (1)

R&#233;gis FLORET
R&#233;gis FLORET

Reputation: 494

You can try to create an "In" filter by your self.

# Somewhere in your template filters and tags

@register.filter
def InList(value, list_):
  return value in list_.split(',)

and in your template:

{% load inlist %}

{% if not '1'|InList:'5,6,7,8,9,10,11,12,13' %}
<div>1 is not inside</div>
{% endif %}

{% if '5'|InList:'5,6,7,8,9,10,11,12,13' %}
<div>5 is inside</div>
{% endif %}

I've just tested it. It works.

br

Upvotes: 5

Related Questions