Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Template Language: Using a for loop with else

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> 
like image 747
Brandon Nadeau Avatar asked Apr 29 '13 20:04

Brandon Nadeau


People also ask

Which Django template syntax allows to use the for loop?

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.

What does {% %} mean in Django?

{% %} 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.

What is Forloop counter in Django?

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.


1 Answers

Use for...empty, which is basically the Django equivalent (replaces the else keyword with empty).

like image 72
mipadi Avatar answered Sep 23 '22 05:09

mipadi