Search code examples
nunjucks

How to join array values surrounded by tags in nunjucks


Code for example:

{% set sites = [
    {name:"StackOverFlow",url:"https://stackoverflow.com/"},
    {name:"ask-Ubuntu",url:"https://askubuntu.com/"}
] %}
{% for site in sites %}
    <a href="{{site.url}}">{{site.name}}</a>, 
{% endfor %}

The result will look like:
StackOverFlow, ask-Ubuntu,

My question is how to prevent the unnecessary , in the end?


Solution

  • You can use loop.last - boolean indicating the last iteration (docs)

    {% set sites = [
        {name:"StackOverFlow",url:"https://stackoverflow.com/"},
        {name:"ask-Ubuntu",url:"https://askubuntu.com/"}
    ] %}
    {% for site in sites %}
        <a href="{{site.url}}">{{site.name}}</a>{% if not loop.last %}, {% endif %} 
    {% endfor %}