Handlebars helper for rendering sub template
by peterbenoit
HTML
<script src="http://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.0.beta.6.js"></script>
<script id="subLevel" type="text/x-handlebars-template">
{{a}}----> {{content}} <----- {{b}}
</script>
<script id="topLevel" type="text/x-handlebars-template">
<p>
{{render_handlebars "subLevel" a=1 b="y"}}
</p>
<p>
{{# applyTemplate "subLevel" a=2 b="z"}}
{{topLevelVar}}
{{/ applyTemplate }}
</p>
</script>
JavaScript
// inline helper
Handlebars.registerHelper('render_handlebars', function(name, context) {
// we need the sub template compiled here
// in order to be able to generate the top level template
var subTemplate = Handlebars.compile($('#' + name).html());
var subTemplateContext = $.extend({},this,context.hash);
return new Handlebars.SafeString(subTemplate(subTemplateContext));
});
// block level helper
Handlebars.registerHelper('applyTemplate', function(name, context){
// we need the sub template compiled here
// in order to be able to generate the top level template
var subTemplate = Handlebars.compile($('#' + name).html());
var innerContent = context.fn(this);
var subTemplateArgs = $.extend({}, context.hash, {content: new Handlebars.SafeString(innerContent)});
return subTemplate(subTemplateArgs)
});
var _template = Handlebars.compile($('#topLevel').html());
$('body').append(_template({topLevelVar:123, content:"cascading"}));