簡體   English   中英

Handlebars.js 使用../ 來引用父上下文

[英]Handlebars.js using ../ to reference parent Context

假設我有以下 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}}指令 ~~無法呈現~~ 呈現空值。

有沒有辦法通過塊助手傳遞父上下文?

改變這個:

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

對此:

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

為什么? 因為 if 語句在內部上下文中,所以首先你需要提升一個級別,這就是為什么你必須添加 ../

查看更多詳細信息: https ://github.com/wycats/handlebars.js/issues/196

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM