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.
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.
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 #}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With