Search code examples
javascripthtmltemplatesnunjucks

Nunjacks icon count macro


I'm using Nunjucks and want to create a macro that plus in star icon and then in the template I can just specify how many stars each element has: e.g:

{{star(4)}}

will display for icon star:

rating: ****

rating: *****

At the moment I don't know how to pass the count:

{% macro starIconTables( star ) %}

    {% for star in stars %}
        <span class="icon icon-star-filled"></span>
    {% endfor %}

{% endmacro %}

Solution

  • You can use range:

    {% macro stars(num) %}
    {%- for i in range(0, num) -%}<span class="icon icon-star-filled"></span>{%- endfor -%} 
    {% endmacro %}
    
    stars: {{ stars(4) }}
    stars: {{ stars(10) }}
    

    P.S. {%- and -%} to remove additional line breakers.