最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Iterate through keysvalues in Hogan.js - Stack Overflow

programmeradmin0浏览0评论

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)?

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)?

Share Improve this question asked Mar 25, 2012 at 22:31 YuviYuvi 4,6678 gold badges37 silver badges43 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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}}

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.pile("{{#list}} {{name}} {{/list}}");
var output = template.render(data);
console.log(output);

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

发布评论

评论列表(0)

  1. 暂无评论