Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can we get an {% empty %} tag? #77

Closed
priestc opened this issue Dec 2, 2011 · 5 comments
Closed

Can we get an {% empty %} tag? #77

priestc opened this issue Dec 2, 2011 · 5 comments

Comments

@priestc
Copy link

priestc commented Dec 2, 2011

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 :(

@mitsuhiko
Copy link
Contributor

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.

@priestc
Copy link
Author

priestc commented Dec 3, 2011

oh, i see. Maybe put a note of that in the "Switching from other Template Engines" under then django section?

njl added a commit to njl/jinja2 that referenced this issue Mar 13, 2012
Points out that the Django empty is replaced by the
Flask else.
@inactivist
Copy link

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...

mitsuhiko added a commit that referenced this issue May 19, 2013
@WloHu
Copy link

WloHu commented Feb 21, 2019

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).

@mitsuhiko
Copy link
Contributor

The else block in Jinja works like the empty block in Django already. No change is necessary here.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants