简体   繁体   English

迭代Hogan.js中的键/值

[英]Iterate through keys/values in Hogan.js

Is there a way to iterate through keys and values in an object using Hogan.js? 有没有办法使用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)? 甚至可以遍历hogan.js(或任何其他moustache.js实现)中的对象?

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. 没有办法直接迭代Hogan.js中对象中的键和值,sub_stantial正在做的是基本上迭代一个数组。

Depending on what you want to do you need a bit of prerender code. 根据您的要求,您需要一些prerender代码。 Supposing you have an object o that is { k1: "v1", k2: "v2" } . 假设你有一个对象o { k1: "v1", k2: "v2" } And you want your rendered template to be k1 has value v1; k2 has value v2; 并且您希望渲染的模板为k1 has value v1; k2 has value v2; 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 而做法的Mustache模板是
{{#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 : 昨天我处于相同的情况,经过对Hogan.jsMustache.js一些研究后,我发现了这个解决方案:

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/ 你可以在这里看到它: http//jsfiddle.net/LuD6j/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM