Is 'if element in aList' possible with Django templates?

流过昼夜 提交于 2019-12-24 05:33:33

问题


Does something like the python

if "a" in ["a", "b", "c"]:
    pass

exist in Django templates?

If not, is there an easy way to implement it?


回答1:


This is something you usually do in your view functions.

aList = ["a", "b", "c"]
listAndFlags = [ (item,item in aList) for item in someQuerySet ]

Now you have a simple two-element list that you can display

{% for item, flag in someList %}
    <tr><td class="{{flag}}">{{item}}</td></tr>
{% endfor %}



回答2:


Not directly, there is no if x in iterable template tag included.

This is not typically something needed inside the templates themselves. Without more context about the surrounding problem a good answer cannot be given. We can guess and say that you want to either pass a nested list like the above comment, or you really just need to do more calculation in the view and pass a single list (testing for empty if you don't want it to do anything).

Hope this helps.



来源:https://stackoverflow.com/questions/1106849/is-if-element-in-alist-possible-with-django-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!