Handlebars {{set}} helper

Set a hash of key/value pairs. Good for convenient storage and retrieval of expression helpers and for referencing parent @variables in child block helpers.

HTML

<script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.3.0/handlebars.min.js"></script>
<script id="template" type="text/x-handlebars-template">
    {{#each people}}
    {{! You can set one or more properties at once, but only one subexpression may be used per set. Because of a handlebars bug, the last subexpression overrides others. }}
    {{set index=@index indexPlus1=(math @index "+" 1)}}
    <ul>
        {{#each hobbies}}
        
        {{! Set multiple properties with subexpressions with separate expressions. }}
        {{set indexPlus1=(math @index "+" 1)}}
        {{set indexMod2=(math @index "%" 2)}}
        <li class="row-color-{{indexMod2}}">Parent index {{../index}}, Person {{../indexPlus1}}, Hobby {{indexPlus1}}: {{hobbyname}}</li>
        {{/each}}
    </ul>
    {{/each}}
</script>

<div id="templateOutput"></div>

CSS

ul {
    margin: 2em;
}
.row-color-0 {
    background-color: burlywood;
    padding: 0.1em;
}
.row-color-1 {
    background-color: blanchedalmond;
    padding: 0.1em;
}

JavaScript

Handlebars.registerHelper('set', function(options) {
    for (var key in options.hash) {
        this[key] = options.hash[key];
    }
});

Handlebars.registerHelper('math', function (x, op, y) {
    x = +x;
    y = +y;
    
    return {
        '+': x + y,
        '-': x - y,
        '*': x * y,
        '/': x / y,
        '%': x % y
    }[op];
});
var context = {
    "people": [
        {
            "name": "John",
            "hobbies": [
                {
                    "hobbyname": "swimming"
                },
                {
                    "hobbyname": "dancing"
                },
                {
                    "hobbyname": "movies"
                }
            ]
        },
        {
            "name": "Jane",
            "hobbies": [
                {
                    "hobbyname": "swimming"
                },
                {
                    "hobbyname": "running"
                },
                {
                    "hobbyname": "painting"
                }
            ]
        },
        {
            "name": "Pat",
            "hobbies": [
                {
                    "hobbyname": "movies"
                },
                {
                    "hobbyname": "hopscotch"
                },
                {
                    "hobbyname": "running"
                }
            ]
        }
    ]
},
    source = $("#template").html(),
    template = Handlebars.compile(source),
    html = template(context);

$("#templateOutput").html(html);