Counting lists?

Take this snippet:

{{#repos}} <b>{{name}}</b> {{/repos}} 

How can I count the number of elements in a repos ?

+4
source share
2 answers

One way is to add logic to JSON itself as a function on this :

 var tmpl = "{{#repos}}<b>{{name}}</b>{{/repos}}({{count}})"; var json = { repos: [{ name: "Tom"}, { name: "Dick"}, { name: "Harry"}], count: function() { return this.repos.length; } }; alert(Mustache.to_html(tmpl, json)); 

http://jsfiddle.net/mblase75/QBzuk/

+4
source

At least for me, I was able to use the ".length" function directly like this: (tested with Mustache v 0.8.1)

 var tmpl = "{{#repos}}<b>{{name}}</b>{{/repos}} ({{repos.length}})"; var json = { repos: [{ name: "Tom"}, { name: "Dick"}, { name: "Harry"}] }; alert(Mustache.to_html(tmpl, json)); 

Alerts " <b>Tom</b><b>Dick</b><b>Harry</b> (3) "

+3
source

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


All Articles