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

前端 未结 3 1192
无人共我
无人共我 2021-01-05 17:03

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

相关标签:
3条回答
  • 2021-01-05 17:53
    {% if sections.0.name == "Social" %}
        Hello Social!
    {% endif %}
    0 讨论(0)
  • 2021-01-05 17:59

    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.

    0 讨论(0)
  • 2021-01-05 18:03

    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 #}
    
    0 讨论(0)
提交回复
热议问题