In the Django template language is there away to use the the else clause with a for loop? I relies I can use an if check before the for loop but that gets repetitive.
python for-else
list = []
for i in list:
print i
else:
print 'list is empty'
Django template for-else (my guess)
<h1>{{ game.title}}</h1>
<table>
<tr>
{% for platform in game.platform_set.all %}
<td>{{ platform.system }} -- ${{ platform.price}}</td>
{% else %}
<td>No Platforms</td>
{% endfor %}
</tr>
</table>
<a href="{% url 'video_games:profile' game.id %}"></a>
To create and use for loop in Django, we generally use the “for” template tag. This tag helps to loop over the items in the given array, and the item is made available in the context variable.
{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.
But Django brings in the box an automatically creates a variable called forloop. counter that holds the current iteration index. {% for variable in variables %} {{ forloop.counter }} : {{ variable.variable_name }} {% endfor %} The forloop.
Use for...empty
, which is basically the Django equivalent (replaces the else
keyword with empty
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With