Overriding Global Partials
With the Handlebars template system, you can register global partial templates. These are the defaults. They can be overridden in certain contexts.
by Adam Boduch
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.3.0/handlebars.min.js"></script>
<!-- The "header" partial template -->
<script id="partial-header" type="x-handlebars-template">
<h2>{{title}}</h2>
</script>
<!-- The custom "header" partion template that isn't registered globally. -->
<script id="partial-header-custom" type="x-handlebars-template">
<h3>{{title}}</h3>
</script>
<!-- The "body" partial template -->
<script id="partial-body" type="text/x-handlebars-template">
<p>{{content}}</p>
<a href="#">Use Custom Header</a>
</script>
<!-- The "footer" partial templateee -->
<script id="partial-footer" type="text/x-handlebars-template">
<small>{{footer}}</small>
</script>
<!-- The main template, composed of partials -->
<script id="main" type="text/x-handlebars-template">
<div>{{> header}}</div>
<div>{{> body}}</div>
<div>{{> footer}}</div>
</script>
JavaScript
// Compile the main template, and the custom header template.
var TemplateMain = Handlebars.compile( $( "#main" ).html() ),
TemplateHeaderCustom = Handlebars.compile( $( "#partial-header-custom" ).html() );
// Register the globally-available default partials.
Handlebars.registerPartial( "header", $( "#partial-header" ).html() );
Handlebars.registerPartial( "body", $( "#partial-body" ).html() );
Handlebars.registerPartial( "footer", $( "#partial-footer" ).html() );
// The variables available to the template context.
var context = {
title: "My Title",
content: "My Content...",
footer: "© 2014"
},
$body = $( "body" );
$body.on( "click a", function( e ) {
// When the link is clicked, re-render the main
// template, passing in the custom "header" partial.
// This overrides the default "header" partial.
$body.html( TemplateMain( context, {
partials: { header: TemplateHeaderCustom }
}));
});
// Initial rendering of the main template.
$body.html( TemplateMain( context ) );