Django:如果在列表模板标签中

时间:2014-09-11 11:27:09

标签: django

是否可以编写一个模板标签来检查列表的内容?

目前我从5到13进行了以下检查,但这非常详细,我需要做9次。

{% 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 %}
    ...
    ...

我试过了

{% 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 %} 

但是收到错误

  

异常值:无法解析余数:   &#39; [&#39; 5&#39;&#39; 6&#39;&#39 7&#39;&#39 8&#39;&#39; 9&#39 ;, &#39; 10&#39;&#39; 11&#39;&#39; 12&#39;&#39; 13&#39;]&#39;从   &#39; [&#39; 5&#39;&#39; 6&#39;&#39 7&#39;&#39 8&#39;&#39; 9&#39 ;, &#39; 10&#39;&#39; 11&#39;&#39; 12&#39;&#39; 13&#39;]&#39;

有什么想法吗?

1 个答案:

答案 0 :(得分:5)

你可以尝试创建一个&#34; In&#34;过滤你自己。

# Somewhere in your template filters and tags

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

并在您的模板中:

{% 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 %}

我刚试过它。有用。

BR