把手部分块作为代码模板

时间:2018-05-07 19:08:44

标签: handlebars.js block partial

我使用gulp进行预编译.hbs。

块内的代码必须插入几个地方。这里的问题是,this被赋值为undefined:

,而不是正确的值
  

无法读取未定义的属性“匹配”

{{#>simpleName}}
{{getSimpleName (lookup ../this @key)}}
{{/simpleName}}

<ul class='{{list-votes}}'>
    {{#each list-items}}
        <hr/>
        <li>
            {{@key}}
            {{#each this}}
                <figure class='{{ @simpleName}}'>
                    <img class="{{getSimpleName (lookup ../this @key)}}__img" src="./images/{{getSimpleName .}}.png" alt="{{.}}" width="48" height="48"/>
                    <figcaption class="title header__title">{{.}}</figcaption>
                </figure>
            {{/each}}
        </li>
    {{/each}}
</ul>

getSimpleName - helper js-function,它返回一个更改的字符串。

我不能在部分区块中使用{{getSimpleName (lookup ../this @key)}}吗?

1 个答案:

答案 0 :(得分:1)

您可以在部分视图中使用 。下面是我的代码,它可以工作。

MYLIST:

const list = [
    {
      name: "A:FN",
      ln: "A:LN"
    },
    {
      name: "B:FN",
      ln: "B:LN"
    }
  ]

主视图(list.handlebars):

{{#each list}}
  {{> sample}}

  From Master: LN: {{getSimpleName this.ln}} <hr/>
{{/each}}

部分视图(sample.handlebars):

From Partial: Name: {{getSimpleName this.name}} <br/>

最终结果:

From Partial: Name: A:FN:ADDED 
From Master: LN: A:LN:ADDED
------------------
From Partial: Name: B:FN:ADDED 
From Master: LN: B:LN:ADDED
------------------

我希望您在查找时遇到特定问题。

或者,您可以使用内联部分来实现此目的:

{{#*inline "sample"}}
  From Partial: Name: {{getSimpleName this.name}} <br/>
{{/inline}}


{{#each list}}
  {{> sample }}

  From Master: LN: {{getSimpleName this.ln}} <hr/>
{{/each}}