JLeno46
JLeno46

Reputation: 1269

for loop with an integer in django's templates tags

In my Django template {{review.stars}} is an integer from 1 to 5, but instead of showing a simple number I want to show a number of star icons equal to the {{review.stars}} integer.

I should write something like:

for n in range(1, review.stars+1):
  add star icon

but obviously I can't write something like that in Django template tags. What's the pythonic way to run a loop a variable number of times?

Upvotes: 0

Views: 472

Answers (1)

Joseph Rajchwald
Joseph Rajchwald

Reputation: 487

You can pass the range from the view to the template and then loop through that. Referencing this SO answer:

View:

render_to_response('template.html', {..., 'stars': range(review.stars), ...}, ...)

Template:


{% for n in stars %}
    # add star icon
{% endfor %}

Upvotes: 1

Related Questions