Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 528
Brenden Avatar asked Aug 14 '11 00:08

Brenden


2 Answers

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.

like image 135
Aaron Dufour Avatar answered Nov 02 '22 23:11

Aaron Dufour


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 #}
like image 30
Gabriel Ross Avatar answered Nov 03 '22 00:11

Gabriel Ross