handlebars - is it possible to access parent context in a partial?

后端 未结 8 1453
旧巷少年郎
旧巷少年郎 2020-12-04 15:40

I\'ve got a handlebar template that loads a partial for a sub-element.

I would need to access a variable from the parent context in the calling template, from within

8条回答
  •  眼角桃花
    2020-12-04 15:49

    I created an each Helper function that includes the parent key/values within the subcontext under the key parentContext.

    http://jsfiddle.net/AndrewHenderson/kQZpu/1/

    Note: Underscore is a dependency.

    Handlebars.registerHelper('eachIncludeParent', function ( context, options ) {
    var fn = options.fn,
        inverse = options.inverse,
        ret = "",
        _context = [];
        $.each(context, function (index, object) {
            var _object = $.extend({}, object);
            _context.push(_object);
        });
    if ( _context && _context.length > 0 ) {
        for ( var i = 0, j = _context.length; i < j; i++ ) {
            _context[i]["parentContext"] = options.hash.parent;
            ret = ret + fn(_context[i]);
        }
    } else {
        ret = inverse(this);
    }
    return ret;
    

    });

    To be used as follows:

    {{#eachIncludeParent context parent=this}}
        {{> yourPartial}}
    {{/eachIncludeParent}}
    

    Access parent context values in your partial using {{parentContext.value}}

提交回复
热议问题