John Abraham
John Abraham

Reputation: 18781

How to handle for/if loops from Jinja2 in Django Tempates

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

Answers (1)

Lo&#239;c
Lo&#239;c

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

Related Questions