ML.
← Posts

Django Template Numeric For Loop

Django Template Numeric For Loop

SeongHwa Lee··1 min read

I was trying to implement something similar to a bingo game in Django. To do that, I needed to know the board size and render an HTML table of size×size cells. The only Django template for loop I knew at the time was one that iterates automatically over the elements of a given object. So I did some digging...

...
render_to_response('foo.html', \{..., 'range': range(10), ...\}, ...)
...
and in the template:

\{% for i in range %\}
...
\{% endfor %\}

\{% endhighlight %\}

There is a way to pass a range from the view.

Or, if you just want to repeat a fixed number of times:

\{% highlight html+django %\}

\{% for i in "1234567" %\}
<option value=\{\{i\}\}> \{\{i\}\}</option>
\{% endfor %\}

\{% endhighlight %\}

There is also a way to use a string like "1234567".

A page actually built with a loop!! ![bingo]({{ site.images }}/bingo.jpg)