获取钥匙的车把 [英] Getting key's in handlebar
本文介绍了获取钥匙的车把的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var data = {
"name": "Jack",
"eventlist": {
"1": {
"title": "Title1"
},
"3": {
"title": "Title2",
}
}
};
HTML
<div class="container">
<ul>
<script id="list_template" type="text/x-handlebars-template">
<li>
</li>
</script>
</ul>
</div>
我正在使用handlebar js进行模板化。我想知道如何遍历数据对象和打印标题以及相应的键1,3
I'm using handlebar js for templating.I wanted to know how can i iterate over data object and print the "title" and also the corresponding keys "1" , "3"
推荐答案
$ c> #each 类似于blockhelper,它将散列/对象上下文的键传递给循环的内部上下文:
You could register a dedicated #each
-like blockhelper which passes the keys of a hash/object-context with the "inner" context of the loop:
// based on the `#each` helper, requires jQuery (for jQuery.extend)
Handlebars.registerHelper('each_hash', function(context, options) {
var fn = options.fn, inverse = options.inverse;
var ret = "";
if(typeof context === "object") {
for(var key in context) {
if(context.hasOwnProperty(key)) {
// clone the context so it's not
// modified by the template-engine when
// setting "_key"
var ctx = jQuery.extend(
{"_key":key},
context[key]);
ret = ret + fn(ctx);
}
}
} else {
ret = inverse(this);
}
return ret;
});
当然,您需要在之前将帮助器注册为 。
Of course, the helper needs to be registered before you render the template.
然后在您的模板中,您可以使用 _key
-place持有人来引用密钥:
Then in your template you can refer the the key with the _key
-place holder:
<script id="list_template" type="text/x-handlebars-template">
{{#each_hash eventlist}}
<li>
<span class="evl-key">{{_key}}</span> -
<span class="evl-title">{{title}}</span>
</li>
{{/each_hash}}
</script>
然后,像其他任何车把模板一样渲染模板:
Then just render the template like any other handlebar template:
var source = $("#list_template").html();
var template = Handlebars.compile(source);
var html = template(data);
$("div.container ul").append(html);
这篇关于获取钥匙的车把的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文