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.
Mustache is a logic-less templating system. It permits you to use pre-written text files with placeholders that will be replaced at run-time with values particular to a given request. For more general information on Mustache, consult the mustache specification.
Mustache is a simple web template system. It is available for many programming languages including Java. Mustache is described as a logic-less because it does not have any explicit control flow statements, such as if and else conditionals or for loops.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With