I'm currently learning how to template using Handlebars and would like some advice about how I would combine the following 2 templates into 1 and update my script so each button still displays the correct set of values?
Templates
<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/
You can check for the existence of each of the variables and render the h1
and released
only if they exist:
<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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.