Reputation: 18781
Working on a legacy project where we're using django templates. How can I translate this for/if syntax from Jinja2 to django:
This Jinja example works as intended but syntax error out in django:
{% for story in stories if story.status == "draft" %}
<h1> {{story.title}} </h1>
{% empty %}
<p> No drafts to see here</p>
{% endfor %}
{% for story in stories if story.status == "published" %}
<h1> {{story.title}} </h1>
{% empty %}
<p> No published stories to see here</p>
{% endfor %}
This will not work with {% empty %}
because the if statement is inside
the scope of the for loop.
{% for story in stories %}
{% if story.status == "draft" %}
<h1> {{story.title}} </h1>
{% endif %}
{% empty %}
<p> No drafts to see here</p>
{% endfor %}
{% for story in stories %}
{% if story.status == "published" %}
<h1> {{story.title}} </h1>
{% endif %}
{% empty %}
<p>No published stories</p>
{% endfor %}
Upvotes: 1
Views: 160
Reputation: 11943
There is some doc for django template system :
https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#if
And this should do :
{% if stories|length %}
{% for story in stories %}
{% if story.status == "published" %}
<h1> {{story.title}} </h1>
{% endif %}
{% endfor %}
{% else %}
<p>Nothing to see here.</p>
{% endif %}
Upvotes: 1