【问题标题】:Handlebars.js using ../ to reference parent ContextHandlebars.js 使用 ../ 来引用父上下文
【发布时间】:2012-10-25 04:38:47
【问题描述】:

假设我有以下 JSON 和 handlebars.js 模板:

JSON

{ 
  rootPath: '/some/path/',
  items:[ {
    title: 'Hello World',
    href: 'hello-world'
  },  {
    title: 'About',
    href: 'about'
  },  {
    title: 'Latest News',
    href: 'latest-news'
  }
}

模板

<script id="test-template" type="text/x-handlebars-template">

  <ul class="nav">
    {{#each items}}
      <li><a href="{{../rootPath}}{{href}}">{{title}}</a></li>
    {{/each}}
  </ul>

</script>

上面的模板有效,直到我想过滤项目 - 假设有 2 个列表一个奇数和另一个偶数,这是一个简单的奇数模板:

<script id="test-template" type="text/x-handlebars-template">

  <ul class="nav">
    {{#each items}}
      {{#isOdd @index}}
        <li><a href="{{../rootPath}}{{href}}">{{title}}</a></li>
      {{/isOdd}}
    {{/each}}
  </ul>

</script>

还有注册的助手:

// isOdd, helper to identify Odd items
Handlebars.registerHelper('isOdd', function (rawValue, options) {
  if (+rawValue % 2) {
    return options.fn(this);
  } else {
    return options.inverse(this);
  }
});

帮助程序按预期工作,仅渲染奇数项,但是对父上下文的引用丢失,因此{{../rootPath}} 指令~~渲染失败~~渲染一个空值。

有没有办法通过块助手传递父上下文?

【问题讨论】:

    标签: javascript templates handlebars.js mustache


    【解决方案1】:

    改变这个:

    <a href="{{../rootPath}}{{href}}">
    

    到这里:

    <a href="{{../../rootPath}}{{href}}">
    

    为什么?因为 if 语句是在内部上下文中,所以首先你需要提升一个级别,这就是为什么你必须添加 ../

    查看更多详情: https://github.com/wycats/handlebars.js/issues/196

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-16
      • 2021-02-03
      • 2015-08-03
      • 1970-01-01
      相关资源
      最近更新 更多