Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mustache

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.

like image 554
John Kane Avatar asked May 24 '11 17:05

John Kane


People also ask

What is mustache language?

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.

What is Java mustache template?

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.


1 Answers

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.

like image 116
Clyde Avatar answered Sep 20 '22 23:09

Clyde