访问Handlebar.js模板中的根上下文

isH*_*tov 30 javascript handlebars.js

是否有任何内置方法可以访问Handlebars.js模板中的根上下文?大多数助手都添加了一个嵌套的上下文,你必须在该上下文中的变量之前编写../来访问它,但如果你有很多的每个,ifs等,那就不太实用了.

小智 61

使用@root.这是在handlebars-v2.0.0.js中

{{@root.somthing.nested_somthing}}
Run Code Online (Sandbox Code Playgroud)


equ*_*nt8 6

一旦用循环(例如每个)更多信息更改上下文,就不可能访问模板的根上下文

但是,有可能访问以前的上下文 '../'

# app/assets/javascript/contents.coffee
body = HandlebarsTemplates['my_hbs_template']({
  view:{
    registryName: 'foo',
    data: {items: {x: 'x'}}
    }
  })
Run Code Online (Sandbox Code Playgroud)

模板:

<!-- app/assets/javascript/templates/my_content.hbs -->
<table class="table">
  <tbody>

  {{#each view.data.items}}
    <tr>
      <td>{{@key}}</td>
      <td>
        Hello from {{../view.registryName}}
      </td>
    </tr>
  {{/each}}
  </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

查看http://handlebarsjs.com/#paths 了解更多信息