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 cl开发者_JAVA技巧osing endfor
instead of the else. Is there any way to use for loops inside conditionals?
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.
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 %}
精彩评论