Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set custom forloop start point in django template

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

like image 255
doniyor Avatar asked Sep 03 '13 22:09

doniyor


People also ask

Can I use range function in Django template?

Ans: We can use the range function but there is no range tag or function in Django template.

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.


1 Answers

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:

  • http://djangosnippets.org/snippets/1357/
  • http://djangosnippets.org/snippets/2147/

Also see:

  • Numeric for loop in Django templates

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.

like image 95
alecxe Avatar answered Oct 20 '22 09:10

alecxe