In Mustache templating is there an elegant way of expressing a comma separated list without the trailing comma?

John Kane picture John Kane · May 24, 2011 · Viewed 39.6k times · Source

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.

Answer

Clyde picture Clyde · Sep 29, 2011

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.