Search code examples
ractivejs

Ractive Numeric For Loop Possible?


I've been looking at the docs, and can't seem to find a way to do the following:

   <script>
      var maxStars = 5 ;
   </script>

   <script id="starryNight" type="text/ractive">
     <ul class="starRating">
      {{#for i=0 until {{maxStars}} }}
          <li class="star"></li>
       {{/for}}
       </ul>
    </script>

The idea being to store numerically, how many stars an item has been given, e.g. in a shopping cart. Then draw the correct number of stars for that item.

If anyone can point me in the right direction, it would be much appreciated.


Solution

  • The issue is converting the number into an iterable value.

    You could go with the pedestrian:

     <ul class="starRating">
      {{#each Array(maxStars) }}
          <li class="star"></li>
      {{/each}}
     </ul>
    

    Or go for something a bit more exciting by encapsulating the max stars in the iterable itself:

     <ul class="starRating">
      {{#each '★★★★★'.split('') }}
          <li class="star"></li>
      {{/each}}
     </ul>