Checking if something exists in items of list variable in Django template

天大地大妈咪最大 提交于 2020-01-01 10:50:18

问题


I have a list of sections that I pass to a Django template. The sections have different types. I want to say "if there is a section of this type, display this line" in my template, but having an issue. What I'm basically trying to do is this.

{% if s.name == "Social" for s in sections %}
    Hello Social!
{% endif %}

But of course that's not working. Any idea how to basically in one line loop through the items in a list and do an if statement?

ADDITIONAL INFO: I could potentially have multiple "Social" sections. What I'm trying to do in the template is say "if there are any social sections, display this div. If not, don't display the div." But I dont want the div to repeat, which is what would happen with the above code.


回答1:


Ideally what you would do is create a list that the template gets as such:

l = [s.name for s in sections]

And in the template, use:

{% if 'Social' in l %}

You're trying to put more logic into a template than they are meant to have. Templates should use as little logic as possible, while the logic should be in the code that fills the template.




回答2:


You can't use list comprehensions in templates:

{% for s in sections %}
  {% if s.name == 'Social' %}
    Hello Social!
  {% endif %} {# closing if body #}
{% endfor %} {# closing for body #}



回答3:


{% if sections.0.name == "Social" %}
    Hello Social!
{% endif %}


来源:https://stackoverflow.com/questions/7054189/checking-if-something-exists-in-items-of-list-variable-in-django-template

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