cbuch1800
cbuch1800

Reputation: 943

Do Django templates allow for range() in for loops?

I am trying to use a for loop in my template but I am getting an error.

Here is the Jinja:

{% for i in range(1,10) %}
    <h2>{{i}}</h2>
{% endfor %}

Here is the error:

django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '(1,10)' from 'range(1,10)'

I am a little confused. This indicates that there is something wrong with range or even that it doesn't exist, yet I have seen it suggested as a solution in other Stack Overflow posts such as this one: How to simulate while loop in Jinja2

Does range exist in Jinja/Django? If yes, why is this not working, and if no, what is the best alternative?

Upvotes: 10

Views: 18701

Answers (4)

djvg
djvg

Reputation: 14365

The other answers suggest one of the following:

  • creating the range in the view, then passing it into the template context
  • creating a custom template filter (or tag) that returns the range
  • iterating over a fixed-length string

However, we could also emulate range() directly in the template by iterating over a variable-length string, using one of the built-in template filters, viz. ljust, rjust, or center:

{% for _ in ''|ljust:number %}
    {{ forloop.counter }}
{% endfor %}

This iterates over a dummy string of length number.

The actual loop index, i.e. the OP's i, can be obtained using forloop.counter or forloop.counter0.

For start indices other than 1 or 0, you can use an if condition inside the loop.

EDIT:

It turns out there already are lots of similar solutions here: Numeric for loop in Django templates

Upvotes: 1

Sunderam Dubey
Sunderam Dubey

Reputation: 8837

First thing, there is no range tag or function in django template.

Answer- Pass the list to the render function.

This was your problem:

{% for i in range(1,10) %}
    <h2>{{i}}</h2>
{% endfor %}

Replace it by passing the range function as generator in views.py

context={
'iterator':range(1,10)
}
return render(req,'anyname.html',context)

Then in your template you can use by following:

{% for i in iterator %}
   <div> {{i}} </div>
{% endfor %}

Upvotes: 3

itnAAnti
itnAAnti

Reputation: 654

In Python a string can be iterated over using a for loop.

For example:

for ch in '0123456789':
    print(ch)

Or, in Django:

{% for ch in '0123456789' %}
    <h2>{{ch}}</h2>
{% endfor %}

Upvotes: 2

Jacob Noble
Jacob Noble

Reputation: 157

I don't think there is an official solution for this. However there are some workarounds.

Something like this would work in the template, the "a" would be the number you'd like to loop over.

{% for x in "aa" %}
   ...
{% endfor %}

Another solution would be to create a custom template filter that you could give a number to and it would return:

range(x)

The final option I can think of is:

render_response('template.html', {'range': range(10))

and then do :

{% for x in range %}
   ...
 {% endfor %}

Upvotes: 10

Related Questions