Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop X times in Django?

I have user reviews on my site. Each review has a rating of 1-5 stars. I want to print that many stars. How do I do it? I only see {% for X in Y %} which lets you iterate over a list, but not a certain number of times.

like image 904
mpen Avatar asked Jun 03 '10 20:06

mpen


People also ask

How do I loop an array in Django?

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. The syntax of using the “for” tag in a template is shown below.

What is Forloop counter in Django?

counter that holds the current iteration index. {% for variable in variables %} {{ forloop.counter }} : {{ variable.variable_name }} {% endfor %} The forloop. counter starts with 1, this means the first entry will start with 1 and increments till the loop iterates.

Can I use while loop in Django?

The key point is that you can't do this kind of thing in the Django template language.


2 Answers

Use the Template range filter by zalun:

from django.template import Library

register = Library()

@register.filter
def get_range( value ):
  """
    Filter - returns a list containing range made from given value
    Usage (in template):

    <ul>{% for i in 3|get_range %}
      <li>{{ i }}. Do something</li>
    {% endfor %}</ul>

    Results with the HTML:
    <ul>
      <li>0. Do something</li>
      <li>1. Do something</li>
      <li>2. Do something</li>
    </ul>

    Instead of 3 one may use the variable set in the views
  """
  return range( value )
like image 98
jball Avatar answered Nov 15 '22 10:11

jball


No need for a custom filter - make_list will do the job:

{% for i in '123'|make_list %}
like image 23
Daniel Roseman Avatar answered Nov 15 '22 08:11

Daniel Roseman