mvc • Mustache {{ templating }} - martindubenet/wed-dev-design GitHub Wiki

Trim function to control the ponctuation of array values

Original problem gets a trailing coma : Item 1, Item 2, Item 3, Item 4,

/**
 * Mustache function file
 */
{
  "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 
    }
  }
}
/**
 * Mustache template file
 */
{{#items}}{{display}}, {{/items}}

<!--
 * DOM rendered (without coma after the last value of the array)
 -->
Item 1, Item 2, Item 3, Item 4