admin管理员组文章数量:1327750
Given this hash
a = {
foo : { ... },
bar : { ... },
zap : { ... }
}
i want to iterate over it but since the keys are different I am not sure how to in Mustache.js
the output will look something like this foo : (contents here)
Given this hash
a = {
foo : { ... },
bar : { ... },
zap : { ... }
}
i want to iterate over it but since the keys are different I am not sure how to in Mustache.js
the output will look something like this foo : (contents here)
Share Improve this question edited Apr 2, 2012 at 19:07 ZeissS 12.1k4 gold badges37 silver badges50 bronze badges asked Apr 2, 2012 at 18:37 samcconesamccone 10.9k7 gold badges44 silver badges50 bronze badges 1-
Can you detail this a bit? Do you want to iterate the elements of
foo
,bar
andzap
or the keys itself? – ZeissS Commented Apr 2, 2012 at 18:44
1 Answer
Reset to default 4If you know the key in the nested object that you're trying to retrieve, you can use a function.
see: http://jsfiddle/jimschubert/zPWDJ/
js:
$(function() {
var names = {
"a": [
{"foo": { "name": "foo name"}},
{"bar": { "name": "bar name"}},
{"zap": { "name": "zap name"}}
],
"n": function() {
var self = this;
var n = "";
Object.keys(self).forEach(function(k, v) {
if (typeof self[k] == "object") {
if(!n) n = self[k]["name"];
}
});
return n;
}
};
var template = $('#template').html();
var out = $('#output');
var html = Mustache.to_html(template, names);
console.log(html);
out.html(html);
});
html:
<script id="template" class="template" type="text/x-mustache">
{{#a}}
<p>{{n}}</p>
{{/a}}
</script>
<h1>Output</h1>
<div id="output">
</div>
This of course assumes your data is an array of objects (the a
in your post would be one key of a greater array, maybe?) If you don't have an array, I don't see why you wouldn't be able to adjust this for an object and make a getter function for whatever properties of each key you're looking for.
本文标签: javascriptHow to Iterate over a hash in mustachejsStack Overflow
版权声明:本文标题:javascript - How to Iterate over a hash in mustache.js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742234623a2437848.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论