Iterate through keys / values ​​in Hogan.js

Is there a way to iterate over keys and values ​​in an object using Hogan.js? I cannot find such documented functionality - only iteration over arrays seems to be documented. Is it even possible to iterate through objects in hogan.js (or any other mustache.js implementation)?

+3


source to share


2 answers


It is not possible to directly iterate over the keys and values ​​in an object in Hogan.js, what sub_stantial does is very important to iterate over the array.

Depending on what you want to do, you need a little prerender code. Suppose you have an object o which is equal to { k1: "v1", k2: "v2" }

. And you want your rendered template to be k1 has value v1; k2 has value v2;

, you only need this (_ is underscore ):



var oAsList = [];
_.each(_.keys(oAsList), function (k) {
  oAsList.push({ key: k, value: o[k] });
})

      

And the Mustache pattern that does the trick is {{#oAsList}} {{key}} has value {{value}}; {{/oAsList}}

+4


source


I was in the same situation yesterday and after some research with Hogan.js

and Mustache.js

I found this solution:

var data = { 'list' : [{ 'name' : 'dhg'}, {'name' : 'abc'}] };
var template = Hogan.compile("{{#list}} {{name}} {{/list}}");
var output = template.render(data);
console.log(output);

      



You can see it in action here: http://jsfiddle.net/LuD6j/1/

+1


source







All Articles