车把部分块作为代码模板

handlebars partial block as a code template

我使用 gulp 预编译 .hbs。

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

而不是正确的值

Cannot read property 'match' of 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 - 辅助 js 函数,它 returns 一个更改的字符串。

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

您可以在局部视图中使用 this。下面是我的代码,它有效。

我的列表:

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}}