8

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.

3 Answers 3

18

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.

Sign up to request clarification or add additional context in comments.

Comments

15

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

2 Comments

Should be s.name == 'Social'.
Maybe I should have included different 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. Thoughts?
-1
{% if sections.0.name == "Social" %}
    Hello Social!
{% endif %}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.