Handlebars helper for rendering sub template

by dain

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">
    <tr><td>{{a}}----> {{content}} <----- {{b}}</td></tr>
</script>

<script id="topLevel" type="text/x-handlebars-template">
  <table>
    {{# applyTemplate "subLevel" a=1 b="y"}}<input type="text" value='a'>{{topLevelVar}}{{/ applyTemplate }}
    {{# applyTemplate "subLevel" a=2 b="z"}}<input type="text" value='b'>{{/ applyTemplate }}      
  </table>
</script>

JavaScript

Handlebars.registerHelper('applyTemplate', function(subTemplateId,ctx){
    
    // we need the sub template compiled here
    // in order to be able to generate the top level template
    var subTemplate =  Handlebars.compile($('#' + subTemplateId).html());
    
    var innerContent = ctx.fn(this);
    var subTemplateArgs = $.extend({}, 
      ctx.hash, 
      {content: new Handlebars.SafeString(innerContent)});

    return subTemplate(subTemplateArgs)
});

var _template =  Handlebars.compile($('#topLevel').html());

$('body').append(_template({topLevelVar:123}));