jsRender: Passing Variables to Nested Templates

by
Annika Backstrom
in misc, on 1 December 2011. It is tagged #Web, #JavaScript, and #jsRender.

jsRender is the in-development successor to jQuery Templates (jquery-tmpl). I've been playing around with it, and have struggled with a clean way to pass additional parameters to nested templates. What I've got so far:

<script id="t-parent" type="text/x-jquery-tmpl">
    <h1>{{=section}}</h1>
    <ul>
        {{#each subsections}}
            <li>{{=subsection}} in {{=$view.parent.parent.data.section}} AKA {{section_name}}</li>
        {{/each}}
    </ul>
</script>

And the relevant JavaScript, including the {{section_name}} template tag:

$.views.registerTags({
    section_name: function() {
        return this._view.parent.parent.data.section;
    }
});

var o = { section: "Sample", subsections: [ { subsection: "Skydiving"}, { subsection: "Skiing"} ] };

$('#container').html($('#t-parent').render(o));

I'm questioning $view.parent.parent.data.section. Seems a bit verbose, but I can't find a cleaner way to step out of the nested template and access variables from the outer scope.

I've posted a jsFiddle of the above.