Django has this really cool tag called {% empty %}, which lets you do this:
{% for item in list %}
<tr><td>{{ item }}</td></tr>
{% empty %}
<tr><td>Nothing to show!</td></tr>
{% endfor %}
which is short for
{% if list %}
{% for item in list %}
<tr><td>{{ item }}</td?</tr>
{% endfor %}
{% else %}
<tr><td>Nothing to show!</td></tr>
{% endif %}
Since switching to jinja, I have really missed this tag :(
That already exists. Use {% else %}
on a for loop. Unfortunately we had else before Django created empty and renaming it now to match Django semantics is kinda weird.
oh, i see. Maybe put a note of that in the "Switching from other Template Engines" under then django section?
I don't see this in the switching documentation. It is mentioned in the control structures:for documentation but it would be helpful to have it in the switching doc...
If list
in code is a generator and for
and if
blocks work in the same way as in Python then the if-for
construct doesn't solve the problem because generators are always truthy, plus such construct is less idiomatic than empty
block.
I don't know if you can add a flag to check if loop has run, check for NameError: name 'item' is not defined
or add helper variable to list(generator)
at Jinja level. If not, then the only solutions is to add the empty
block or convince Python devs that empty generators should be falsy (to avoid ugly checking by handling StopIteration
and "pushing back" popped item).
The else
block in Jinja works like the empty
block in Django already. No change is necessary here.
Most helpful comment
That already exists. Use
{% else %}
on a for loop. Unfortunately we had else before Django created empty and renaming it now to match Django semantics is kinda weird.