Reputation: 2944
In Marionette with Underscore templates, is it possible to 'include' one template file into another template file - so that common markup can be shared across multiple templates?
We use requireJS to load the .tpl files as and when - and then assign a tpl file to a Marionette view;
View.MyView = Marionette.ItemView.extend({
template: 'parent_template.tpl'
});
Where 'parent_template.tpl' contains something like.
<h1>A Parent View</h1>
<button class='btn-one'>One</button>
<button class='btn-two'>Two</button>
<button class='btn-three'>three</button>
What I would like to do is extract say the buttons to a common tpl, that other tpl's could use, something like...
Where 'parent_template.tpl' contains something like.
<h1>A Parent View</h1>
{{child_template.tpl}}
And 'child_template.tpl' contains something like.
<button class='btn-one'>One</button>
<button class='btn-two'>Two</button>
<button class='btn-three'>three</button>
And then lots of other templates could pull in the shared template.
Any ideas?
Upvotes: 1
Views: 1670
Reputation: 451
For me it smells odd including template in template. You can instead use Mariontte.LayoutView with subview:
buttons subview :
Buttons = Marionette.ItemView.extend({
template: 'child_template.tpl'
});
layout :
MyView = Marionette.LayoutView.extend({
template: 'parent_template.tpl',
region : {
buttonRegion : '.myButtonsRegion'
},
onShow : function(){
var buttons = new Buttons();
this.buttonRegion.show(buttons);
}
});
and then parent_template.tpl :
<h1>A Parent View</h1>
<div class="myButtonsRegion"></div>
Upvotes: 1
Reputation: 2944
The way that I solved this was with templateHelpers.
Load the partial templates as per usual with require JS. Then pass a reference to the child template into the parent template via the templateHelper;
define(['tpl!parent.tpl', 'tpl!child.tpl'], function (ParentTemplate, ChildTemplate) {
View.MyView = Marionette.View.extend({
template: ParentTemplate,
templateHelpers: function() {
return {
childTpl: ChildTemplate
}
}
});
}
The parent template includes the child via the helper
<h1>parent template</h1>
<%= childTpl(obj) %>
The child can access the data if you pass 'obj' - the template model
<h2>this is the child, that can access the parent data <%= title %></h2>
Upvotes: 2