Cameron A Cameron A - 3 months ago 9
Python Question

Set a condition from inside of a loop Jinja2

<ul>
{% for bm in user.bookmarks %}
<li>
<a href="{{ bm.url }}">{{ bm.description }}</a>
</li>
{% else %}
<li>This user has not added any bookmarks yet.</li>
{% endfor %}
</ul>


Is there a way to set a condition from inside of the loop
I mean if 'for loop' doesnt have any result the ul tag dont generate into page

The whole idea is preventing putting empty tag in the page
I know I can put another if expression outside but It is so complicated for maintenance

Answer

You can put the ul tags inside the loop, and use the loop.first and loop.last variables to control them.

{% for bm in user.bookmarks %}
  {% if loop.first %}
    <ul>
  {% endif %}
      <li>
          <a href="{{ bm.url }}">{{ bm.description }}</a>
      </li>
  {% if loop.last %}
    </ul>
  {% endif %}
{% else %}
   This user has not added any bookmarks yet.
{% endfor %}