Lisa
Lisa

Reputation: 43

How to use a for loop inside a Django conditional?

Basically if there is a certain GET parameter in the url (in this case "latest") I want to slice the object list by a different number than the usual. But doing this:

    {% if 'latest' in request.GET %}
        {% for object in object_list|slice:"22" %}
    {% else %}
        {% for object in object_list|slice:"10" %}
    {% endif %}

         // blah blah

    {% endfor %}

causes a syntax error since Django expects a closing endfor instead of the else. Is there any way to use for loops inside conditionals?

Upvotes: 0

Views: 236

Answers (2)

rolling stone
rolling stone

Reputation: 13016

Just close the for loop inside each conditional:

{% if 'latest' in request.GET %}
    {% for object in object_list|slice:"22" %}
        {{ object.name }}
    {% endfor %}

{% else %}
    {% for object in object_list|slice:"10" %}
        {{ object.name }}
    {% endfor %}
{% endif %}

Upvotes: 0

David Ly
David Ly

Reputation: 31586

You need to have a body in your for loop.

{% if 'latest' in request.GET %}
    {% for object in object_list|slice:"22" %} {{ object }} {% endfor %}
{% else %}
    {% for object in object_list|slice:"10" %} {{ object }} {% endfor %}
{% endif %}

Without it, you're saying the equivalent of the following Python code:

if 'latest' in request.GET:
    for object in slice(object_list, 22):
        #No code here
else:
    for object in slice(object_list, 10):
        #No code here

which obviously is an error.

Upvotes: 2

Related Questions