如何在 mustache.js 中迭代哈希 [英] How to Iterate over a hash in mustache.js
问题描述
给定这个哈希
a = {foo : { ... },酒吧 : { ... },电击:{ ... }}
我想迭代它,但由于键不同,我不确定如何在 Mustache.js
输出看起来像这样 foo :(这里的内容)
如果您知道要检索的嵌套对象中的键,则可以使用函数.
参见:http://jsfiddle.net/jimschubert/zPWDJ/
js:
$(function() {变量名称 = {一种": [{"foo": { "name": "foo name"}},{"bar": { "name": "bar name"}},{"zap": { "name": "zap name"}}],n":函数(){var self = this;var n = "";Object.keys(self).forEach(function(k, v) {if (typeof self[k] == "object") {if(!n) n = self[k]["name"];}});返回 n;}};var template = $('#template').html();var out = $('#output');var html = Mustache.to_html(模板,名称);控制台日志(html);out.html(html);});
html:
<h1>输出</h1><div id="输出">
这当然假设你的数据是一个对象数组(你帖子中的 a
可能是更大数组的一个键,也许?)如果你没有数组,我不不明白为什么你不能为一个对象调整它,并为你正在寻找的每个键的任何属性创建一个 getter 函数.
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)
If you know the key in the nested object that you're trying to retrieve, you can use a function.
see: http://jsfiddle.net/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.
这篇关于如何在 mustache.js 中迭代哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!