句柄 - 是否有可能在部分访问父上下文? [英] handlebars - is it possible to access parent context in a partial?

查看:77
本文介绍了句柄 - 是否有可能在部分访问父上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我需要从调用模板的父上下文访问一个变量。

我有一个句柄模板,为子元素加载一个局部变量。 ,从部分内。 .. 似乎无法解析部分内的任何内容。



简化代码如下所示:



模板

  {{#each items}} 
{{> item-template}}
{{/ each}}

/ strong>

 值为{{value}} 

(显然,真正的代码更复杂,但它的原理相同,在部分中.. 似乎是未定义的。 )






为了表明它是未定义的,我使用了一个非常简单的助手 whatis 像这样:

$ p $ Handlebars.registerHelper('whatis',function(param){
console。日志(param);
});

并将上述代码更新为:

更新模板

  {{#each items}} 
{{whatis。 。}}< - 控制台显示正确的父上下文
{{> item-template}}
{{/ each}}

/ strong>


$ b $

 {{whatis ..}}<  - 控制台显示未定义
值为{ {value}}

有没有办法解决这个问题?我错过了什么?



编辑:

以防万一任何人在这个问题上磕磕绊绊。这个功能现在存在于Handlebars中。



这样做:

  { {#each items}} 
{{!将项目中的当前项目传递给您的部分}}
{{> item-template this}}
{{/ each}}


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 the partial. .. doesn't seem to resolve to anything inside the partial.

Simplified code goes like this:

the template

    {{#each items}} 
        {{> item-template}}
    {{/each}}

the partial

    value is {{value}}

(obviously the real code is more complicated but it's the same principle, within the partial .. appears to be undefined.)


To show it's undefined, I've used a very simple helper whatis like this:

Handlebars.registerHelper('whatis', function(param) {
    console.log(param);
});

and updated the above code to this:

updated template

    {{#each items}} 
        {{whatis ..}}  <-- Console shows the correct parent context
        {{> item-template}}
    {{/each}}

updated partial

    {{whatis ..}}  <-- Console shows "undefined"
    value is {{value}}

Is there a way to go around that issue? Am I missing something?

EDIT: There's an open issue relating to this question on handlebars' github project

解决方案

Just in case anyone stumbles across this question. This functionality exists now in Handlebars.

Do this:

{{#each items}} 
    {{! Will pass the current item in items to your partial }}
    {{> item-template this}} 
{{/each}}

这篇关于句柄 - 是否有可能在部分访问父上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆