Brenden
Brenden

Reputation: 8774

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

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.

Upvotes: 8

Views: 23185

Answers (3)

Gabriel Ross
Gabriel Ross

Reputation: 5198

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 #}

Upvotes: 15

mossplix
mossplix

Reputation: 3865

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

Upvotes: -1

Aaron Dufour
Aaron Dufour

Reputation: 17535

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.

Upvotes: 18

Related Questions