Syed Syed - 7 days ago 4
Python Question

Jinja2 - add class using range inside for loop

This prints as many stars that's passed in

review.rating


<div class="ratings">
{% for review reviews') %}
{% for n in range(review.rating) %}
<span class="review-star review-star-active">★</span>
{% endfor %}
{% endfor %}
</div>


The output that I can get with the above code is:

<div class="ratings">
<span class="review-star review-star-active">★</span>
<span class="review-star review-star-active">★</span>
<span class="review-star review-star-active">★</span>
</div>


But the output I needed is:

<div class="ratings">
<span class="review-star review-star-active">★</span>
<span class="review-star review-star-active">★</span>
<span class="review-star review-star-active">★</span>
<span class="review-star">★</span>
<span class="review-star">★</span>
</div>


I am not sure how can I do it. Thanks in advance.

Answer

Always loop five times, but compare the current counter with the rating and output the active class if it is less or equal.

{% for n in range(5) %}
  <span class="review-star {% if n <= review.rating %}review-star-active{% endif %}">★</span>
{% endfor %}