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

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.


Hrm, doubtful, the mustache demo pretty much shows you, with the first property, that you have to have the logic inside the JSON data to figure out when to put the comma.

So your data would look something like:

{
  "items": [
    {"name": "red", "comma": true},
    {"name": "green", "comma": true},
    {"name": "blue"}
  ]
}

and your template

{{#items}}
    {{name}}{{#comma}},{{/comma}}
{{/items}}

I know it's not elegant, but as mentioned by others Mustache is very lightweight and does not provide such features.


Cheat and use CSS.

If your model is:

{
  "items": [
    {"name": "red"},
    {"name": "green"},
    {"name": "blue"}
  ]
}

then make your template

<div id="someContainer">
{{#items}}
    <span>{{name}}<span>
{{/items}}
</div>

and add a little bit of CSS

#someContainer span:not(:last-of-type)::after {
  content: ", "    
}

I'm guessing someone will say that this is a bad case of putting markup in the presentation but I don't think it is. Comma separating values is a presentation decision to make interpreting the underlying data easier. It's similar to alternating the font color on entries.

Tags:

Mustache