我目前正在学习如何使用Handlebars进行模板设计,并希望了解如何将以下2个模板合并为1并更新我的脚本,以便每个按钮仍显示正确的值集?
模板
<script type="text/x-handlebars" id="infoTemp">
{{#each films}}
<li>
<h2>{{title}}</h2>
<p>{{{description}}}</p>
</li>
{{/each}}
</script>
<script type="text/x-handlebars" id="additionalInfoTemp">
{{#each films}}
<li>
<h1>{{id}}</h1>
<h2>{{title}}</h2>
<p>{{{description}}}</p>
<small>{{released}}</small>
</li>
{{/each}}
</script>
JS
// Dummy data
data = {
"films": [
{
"id": "1",
"title": "The Shawshank Redemption",
"description": "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.",
"released": "2012-09-17 00:00:00"
},
{
"id": "2",
"title": "The Godfather",
"description": "The aging <b>patriarch of an organized</b> crime dynasty transfers control of his clandestine empire to his reluctant son.",
"released": "2012-09-17 00:00:00"
}
]
}
var $info = $('#info');
var source;
//Grab contents of template
function templateData(id){
if( id == 'add1' ){
source = $("#infoTemp").html();
} else {
source = $("#additionalInfoTemp").html();
}
var template = Handlebars.compile(source);
$info.append(template(data));
}
//Grab the container div and insert the templated data in
$('button').on('click', function(e){
var thisData = $(this).data('id');
$info.html('');
templateData(thisData);
e.preventDefault();
});
JS Fiddle http://jsfiddle.net/2TpJh/2/
答案 0 :(得分:0)
您可以检查每个变量是否存在,并仅在h1
和released
存在时进行渲染:
<script type="text/x-handlebars" id="additionalInfoTemp">
{{#each films}}
<li>
{{#id}}<h1>{{.}}</h1>{{/id}}
<h2>{{title}}</h2>
<p>{{{description}}}</p>
{{#released}}<small>{{.}}</small>{{/released}}
</li>
{{/each}}
</script>