There is a forloop in java where i can tell where to start and where to end:
for(int i=10;i<array.length;i++){
}
but how can i implement this int i=10
in django template? How can i set the starting and ending point on my own?
there is a forloop.first
and forloop.last
, but they are defined inside the loop and i cannot do something like this?:
{{forloop.first=10}}
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
{{forloop.last=20}}
I read the django doc but this feature seems to be not there
Ans: We can use the range function but there is no range tag or function in Django template.
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.
How about using built-in slice filter:
{% for athlete in athlete_list|slice:"10:20" %}
<li>{{ athlete.name }}</li>
{% endfor %}
If you need to make a numeric loop (just like python's range
), you need a custom template tag, like this one: http://djangosnippets.org/snippets/1926/
See other range
snippets:
Also see:
By the way, this doesn't sound like a job for templates - consider passing a range from the view. And, FYI, there was a proposal to make such tag, but it was rejected because it is trying to lead to programming in the template.
- think about it.
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