In Mustache templating is there an elegant way of expressing a comma separated list without the trailing comma?
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.
Solution 1:
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.
Solution 2:
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.
Solution 3:
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.
Solution 4:
If you happen to be using jmustache, you can use the special -first
or -last
variables:
{{#items}}{{name}}{{^-last}}, {{/-last}}{{/items}}