I am using the Mustache templating library and trying to generate a comma separated list without a trailing comma, e.g.
red, green, blue
Creating a list with the trailing comma is straightforward, given the structure
{
"items": [
{"name": "red"},
{"name": "green"},
{"name": "blue"}
]
}
and the template
{{#items}}{{name}}, {{/items}}
this will resolve to
red, green, blue,
However I cannot see an elegant way of expressing the case without the trailing comma. I can always generate the list in code before passing it into the template, but I was wondering whether the library offers an alternative approach such as allowing you to to detect whether it is the last item in a list within the template.
I think a better way is to change the model dynamically. For example, if you are using JavaScript:
model['items'][ model['items'].length - 1 ].last = true;
and in your template, use inverted section:
{{#items}}
{{name}}{{^last}}, {{/last}}
{{/items}}
to render that comma.