Iterate through keys/values in Hogan.js

﹥>﹥吖頭↗ 提交于 2019-12-14 04:17:00

问题


Is there a way to iterate through keys and values in an object using Hogan.js? I'm unable to 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 moustache.js implementation)?


回答1:


There is no way to directly iterate over the keys and values in an object in Hogan.js, what sub_stantial is doing is essentialy iterating over an array.

Depending on what you want to do you need a bit of prerender code. Supposing you have an object o that is { 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 the underscore library):

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

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




回答2:


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/



来源:https://stackoverflow.com/questions/9864679/iterate-through-keys-values-in-hogan-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!