Handlebars helper for rendering sub template
by peterbenoit
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.3.0/handlebars.js"></script>
<script id="panelOne" type="text/x-handlebars-template">
{{#entries}}<li>{{title}}</li>{{/entries}}
</script>
<script id="topLevel" type="text/x-handlebars-template">
<p>
{{sub-template "panelOne"}}
</p>
</script>
JavaScript
var data = {
"entries": [{
"title": "Good Medicine Can Be Bad for Baby (short version)",
"description": "Some medicines that are used to treat a woman’s medical conditions can have adverse effects on her unborn child. In this podcast Dr. Cheryl Broussard discusses the potential link between birth defects and women taking medications during pregnancy. Created: 1\u002F14\u002F2011 by MMWR. Date Released: 1\u002F14\u002F2011. Series Name: A Cup of Health with CDC.",
"link": "http:\u002F\u002Fwww2c.cdc.gov\u002Fpodcasts\u002Fplayer.asp?f=4992117",
"downloadlink": "http:\u002F\u002Fwww2c.cdc.gov\u002Fpodcasts\u002Fdownload.asp?af=h&f=8621564",
"pubdate": "2011-01-14T00:00:00-05:00",
"language": "en-US",
"enclosureurl": "",
"categories": ["Birth Defects"]
}]};
// inline helper
Handlebars.registerHelper('sub-template', 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(data));