5

I'm trying to display an array of items with Mustache, and I'd like to show them with a comma separator.

Here is my object :

{"items": [
    {"display": "Item 1"},
    {"display": "Item 2"},
    {"display": "Item 3"},
    {"display": "Item 4"}
]}

And here's my Mustache JS template :

{{#items}}{{display}}, {{/items}}

Unfortunately, this will render as :

Item 1, Item 2, Item 3, Item 4, 

I'd like to remove the last ", ", since it seems odd visually.

I tried with functions, but I got the "{{items}}" text, not the array items.

How can I do this?

1

2 Answers 2

6

You could use a Mustache function. These are defined in your template like any other section, then run on the content they're wrapped around. For your case it would look something like this:

{
  "items": [
    {"display": "Item 1"},
    {"display": "Item 2"},
    {"display": "Item 3"},
    {"display": "Item 4"}
  ],
  "trim": function () {
    return function (text, render) {
      return render(text).replace(/(,\s*$)/g, ''); // trim trailing comma and whitespace 
    }
  }
}

Then your Mustache markup will look like this:

{{#trim}}{{#items}}{{display}}, {{/items}}{{/trim}}

And your output will be what you're after:

Item 1, Item 2, Item 3, Item 4

Check it out on jsfiddle.

1

well i know 2 ways of solve this, first is to program your own iterator helper (and this is the best solution), and the sencond, is to delete manually (with DOM Handling) the trailing coma.

just find the text with your javascript ($("selector").html()), and slice it.

var html = jQuery("selector").html();
html = html.slice(0, html.length-1);

that way you cut the last character.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.