mustache

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

  • 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.