Dani-Br
Dani-Br

Reputation: 2457

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?

Upvotes: 1

Views: 1754

Answers (1)

xmojmr
xmojmr

Reputation: 8145

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 %}

Upvotes: 3

Related Questions