Reputation: 24063
How can I create a template inside a template in handlebars?
Those are my templates:
<script type="text/x-handlebars-template" id="animal-template">
<div class="locationSelect">
{{content}}
</div>
</script>
<script type="text/x-handlebars-template" id="cat-template">
<div>
I am cat
</div>
</script>
<script type="text/x-handlebars-template" id="dog-template">
<div>
I am dog
</div>
</script>
I want to load the appropriated template at runtime (cat-template or dog-template) inside animal-template. How can I do this?
Upvotes: 3
Views: 6100
Reputation: 4209
Partials come in handy when you have a chunk of a Handlebars.js template that you need to use in a few different contexts
<script id="people-template" type="text/x-handlebars-template">
{{#each people}}
{{> person}}
{{/each}}
</script>
<script id="person-partial" type="text/x-handlebars-template">
<div class="person">
<h2>{{first_name}} {{last_name}}</h2>
<div class="phone">{{phone}}</div>
<div class="email"><a href="mailto:{{email}}">{{email}}</a></div>
<div class="since">User since {{member_since}}</div>
</div>
</script>
<script type="text/javascript">
$(document).ready(function() {
var template = Handlebars.compile($("#people-template").html());
Handlebars.registerPartial("person", $("#person-partial").html());
template(yourData);
}
</script>
http://blog.teamtreehouse.com/handlebars-js-part-2-partials-and-helpers
Upvotes: 7
Reputation: 9236
You can compute templateName
's item view property according to the rendered item:
App.AnimalView = Ember.View.extend({
templateNameBinding: function () {
var kind = this.get('animal.kind');
return '%@-template'.fmt(kind);
}.property('animal.kind')
});
Then in the container template, render the items through their view:
<script type="text/x-handlebars-template" id="animal-template">
<div class="locationSelect">
{{#for animal in content}}
{{view App.AnimalView animalBinding="animal"}}
{{/for}}
</div>
</script>
Upvotes: 2