把手范围问题:无法从嵌入的`each`

时间:2015-09-26 11:14:56

标签: javascript html templates handlebars.js keystonejs

我想弄清楚为什么我无法从我的把手模板中嵌入的each语句中访问我的模板变量(在我的keystone项目中呈现)。我在StackOverflow上已经阅读了很多类似问题的问题,但没有一个解决了我的特定用例。

我有一个简单的数据对象,它被传递给Handlebars模板,看起来大致如下:

{ 
   rootPath: '../../../', 
   navigation: { all: { 'a': { sublinks: [Object] }
}

我的问题是:

为什么rootPath模板变量在{{#each navigation.all}}中完美打印,但在{{#each sublinks}}内无法访问?

这是我的Handlebars模板:

<!-- rootPath prints fine here -->
Here is your rootPath variable: {{rootPath}}

{{#each navigation.all}}

    <!-- rootPath prints fine here -->
    top-level rootPath: {{../rootPath}}

    {{#if sublinks}}

            {{#each sublinks}}

                <!-- WHY WON'T ROOTPATH PRINT HERE?? -->
                <!-- Obviously, I am trying the three possible scope paths -->
                sub-level rootPath attempt 1: {{../../rootPath}}
                sub-level rootPath attempt 2: {{../rootPath}}
                sub-level rootPath attempt 3: {{rootPath}}

            {{/each}}

    {{/if}}

{{/each}}

我得到以下输出(请注意所有子级别尝试无法访问rootPath模板变量)

Here is your rootPath variable: ../../../
top-level rootPath: ../../../
sub-level rootPath attempt 1:
sub-level rootPath attempt 2:
sub-level rootPath attempt 3:

我需要的是rootPath随处可用,所以我可以得到这样的内容:

Here is your rootPath variable: ../../../
top-level rootPath: ../../../
sub-level rootPath: ../../../

那么我在这里缺少什么范围问题或语法?

我正在使用Handlebars版本2.0.0,因为这是keystone预先打包的内容。

1 个答案:

答案 0 :(得分:6)

我能够使用@root令牌来解决问题。

只需在嵌入式@root.rootPath中调用{{#each sublinks}}即可解决我的问题。

以下是正确的模板标记:

Here is your rootPath variable: {{rootPath}}

{{#each navigation.all}}

    top-level rootPath 1: {{../rootPath}}      <!-- works -->
    top-level rootPath 2: {{@root.rootPath}}   <!-- works -->

    {{#if sublinks}}

            {{#each sublinks}}
                sub-level rootPath 1: {{@root.rootPath}}  <!-- works -->
                sub-level rootPath 2: {{../../rootPath}}  <!-- doesn't work -->
            {{/each}}

    {{/if}}

{{/each}} 

产生以下输出:

Here is your rootPath variable: ../../../
top-level rootPath 1: ../../../
top-level rootPath 2: ../../../
sub-level rootPath 1: ../../../
sub-level rootPath 2: 
顶级rootPath的

注意:(在{{#each navigation.all}}中,我可以使用其中任何一个:

{{../rootPath}}      <!-- works -->
{{@root.rootPath}}   <!-- works -->

,在嵌入式{{#each sublinks}}中,只有@root.rootPath似乎有效:

{{@root.rootPath}}  <!-- works -->
{{../../rootPath}}  <!-- doesn't work -->