Custom Handlebars include

With parent context, @index, and @key support

by mpetrovich

HTML

<script src="https://dl.dropbox.com/u/22528488/handlebars.js"></script>
<div id="result"></div>

JavaScript

Handlebars.registerHelper("include", function(name, context, options) {
    if (arguments.length < 3) {
        // Context omitted, assumed to be 'this'
        context = this;
    }
    
    context.__ = options.hash.parent || {};
    if (options.hash.index !== undefined) {
        context["_index"] = options.hash.index;
    }
    if (options.hash.key !== undefined) {
        context["_key"] = options.hash.key;
    }
    
    return new Handlebars.SafeString(
        Handlebars.compile("{{> " + name + "}}")(context)
    );
});


var template, compiled, rendered;


// Example with @key
Handlebars.registerPartial(
    "child", "{{_key}}'s parents are {{__/mother}} and {{__/father}}.\n"
);
compiled = Handlebars.compile(
    '{{#each children}}{{include "child" this parent=.. key=@key}}{{/each}}'
);
rendered = compiled({
    father: "Bob",
    mother: "Mary",
    children: {
        John: { age: 9 },
        Jill: { age: 4 }
    }
});
$("#result").append("<pre>" + rendered + "</pre>");
    
    
// Example with @index  
Handlebars.registerPartial(
    "child2", "Child #{{_index}}: {{name}}'s parents are {{__/mother}} and {{__/father}}.\n"
);
compiled = Handlebars.compile(
    '{{#each children}}{{include "child2" this parent=.. index=@index}}{{/each}}'
);
rendered = compiled({
    father: "Bob",
    mother: "Mary",
    children: [
        { name: "John", age: 9 },
        { name: "Jill", age: 4 }
    ]
});
$("#result").append("<pre>" + rendered + "</pre>");