Just learning Django, and I’m trying to create a situation where when a template has layouts it’ll list them, but if it doesn’t it won’t and will instead state that there are none.
I got an error message when I used only a “for layout…” statement on templates that had no layouts.
I figured things out to the point that I created an “if” statement to first check and see if the pages had layouts, and if not, an “else” statement to say that there are none.
The end result, though, is that the “for” seems to be completely ignored, and the “else” condition is applied on all pages — whether or not they have associated layouts.
Code:
{% block header %}
<h1>The name of this template? It's {{ boilerplate.name }}.</h1>
{% endblock %}
{% block content %}
<p> </p>
<p>{{ boilerplate.content }}</p>
{% if layout in boilerplate.layouts %}
{% for layout in boilerplate.layouts.all %}
<p><a href="{{ layout.file.url }}">{{ layout.user }} -- {{ layout.name }} ({{ layout.file.size }})</a>
{% endfor %}
{% else %}
<p>There are no layouts for this template.</p>
{% endif %}
{% endblock %}
There’s obviously something I’m missing. Possibly something very simple. What am I dong wrong?
Your
{% if layout in boilerplate.layouts %}is what’s wrong, but there’s an easier way to achieve this than using an additionaliftag.As the documentation shows, you can use an optional
emptytag to handle situations when you have no layouts. Rewriting your example code: