Adhesive / Bonding with Mustache JS

I am trying to display an array of elements using Mustache and I would like to display them with a comma delimiter.

Here is my object:

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

And here is my Mustache JS template:

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

Unfortunately, this will look like:

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

I would like to remove the last "," as it seems strange visually.

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

How can i do this?

Thank you for your help!

+4
source share
2 answers

I know two ways to solve this problem: first program your own iterator helper (and this is the best solution), and sencond - remove the final coma manually (using DOM Handling).

just find the text using javascript ( $("selector").html() ) and slice it.

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

this way you cut out the last character.

+1
source

You can use the Mustache function. They are defined in your template, as in any other section, and then run on the content that they wrap. 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 Usa markup will look like this:

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

And your result will be what you will be:

 Item 1, Item 2, Item 3, Item 4 

Check it out on jsfiddle .

+4
source

Source: https://habr.com/ru/post/1439123/


All Articles