Search code examples
phptwig

Twig - How to render an HTML rating element


What I am trying to achieve is to render a simple 5-star rating HTML element based on a number ( 0-5 )

Example :

 {{ user.rating }} // returns integer 4

Output should be:

<div class="rating">
     <i class="star voted"></i>
     <i class="star voted"></i>
     <i class="star voted"></i>
     <i class="star voted"></i>
     <i class="star-empty"></i>
</div>
// 4 lighted stars out of 5

Thanks


Solution

  • You can archive your problem with this code:

    <div class="rating">
    {% for i in 1..5 %}
    {% set starClass = (user.rating >= i ? "star voted" : "star-empty")  %}
         <i class="{{ starClass }}"></i>
    {% endfor %}
    </div>
    

    See the working solution on this twigfiddle

    Explanation:

    From the doc:

    If you do need to iterate over a sequence of numbers, you can use the .. operator:

    {% for i in 0..10 %}
        * {{ i }}
    {% endfor %}
    

    The Twig built-in .. operator is just syntactic sugar for the range function.