HUGO

[SOLVED] Range over a number

So, I’m trying to achieve the following (simplified):

[[review]]
person = "Foo Bar"
text = "Almost perfect!"
rating = "4"

[[review]]
person = "Bar Foo"
text = "Perfect!"
rating = "5"
{{ range $i, $review := .Site.Data.reviews.review }}
<div class="review">
    <p>{{ $review.text }} by {{ $review.person }}</p>
    {{ range $j, $rating := $review.rating }}
    <span class="rating-star full-star"></span>  <!-- ★ -->
    <span class="rating-star full-star"></span>  <!-- ★ -->
    <span class="rating-star full-star"></span>  <!-- ★ -->
    <span class="rating-star full-star"></span>  <!-- ★ -->
    <span class="rating-star empty-star"></span> <!-- ☆ -->
    {{ end }}
</div>
{{ end }}

But this throws with range can't iterate over 4.

So basically I’m already looping for each review and get the other values.
But I need to output 4 full-stars if rating is 4 and the remaining using empty-star.
For the remaining part, I know how to do it if the loop worked I’d use len.

How can I just loop x times where x is the rating value?

Thanks in advance for any suggestions!

[[Not tested]]

Also note that your rating is in quotes; i.e., it’s a string and not an integer, hence the use of int below:

{{ range $i, $review := .Site.Data.reviews.review }}
<div class="review">
    <p>{{ $review.text }} by {{ $review.person }}</p>
    {{ range seq 5 }}
         {{if lt . (add (int $review.rating) 1)}} 
         <span class="rating-star full-star"></span>  <!-- ★ -->
         {{ else }}
         <span class="rating-star empty-star"></span> <!-- ☆ -->
         {{ end }}
    {{ end }}
</div>
{{ end }}
1 Like

Damn, that was fast! Many thanks! I was already playing with seq but I was circling around with complex solutions. Yours is short and works perfectly!

1 Like