Reputation: 13425
I'm working with underscore.js and backbone to create some views for an app. The views all have the same first couple of lines, but then differ depending on what type of subclass they are. Is there an efficient way to combine templates, so that I could have a singular "master" template that gets inserted into all of the others?
Code example:
<script type="text/template" id="template-1">
{{ name }}
<span>{{ type }}</span>
<div>
<some view specific html>
</div>
</script>
<script type="text/template" id="template-2">
{{ name }}
<span>{{ type }}</span>
<div>
<some view specific html>
</div>
</script>
Upvotes: 2
Views: 1259
Reputation: 264
I think there's two approaches you could take:
You can represent your 'master' as a different template, and compose it with the child (e.g. with jQuery.append) when you render your view.
Or, an underscore template can render arbitrary javascript, therefore I don't think there's anything stopping you from rendering a template within a template, something like:
<%= data.name %>
<span><%= data.type %></span>
<div>
<%= _.template(data.child, data, { variable: 'data' }) %>
</div>
Or the other way around:
<%= _.template(data.common, data) %>
<div>
Template 1!
</div>
I've added a jsFiddle to demonstrate the first template example in action.
Upvotes: 4