基于查找的车把状况

Jiv*_*van 3 javascript handlebars.js

我有以下数据结构:

{
    things: [
        "desk",
        "chair",
        "pen",
        "book",
        "lamp"
    ],
    owners: [
        "Julia",
        "Sandra",
        "John",
        "Paul"
    ]
}
Run Code Online (Sandbox Code Playgroud)

工作原理:

handleblars模板:

{{#each things}}
    <p>This {{this}} belongs to {{lookup ../owners @index}}</p>
{{/each}}
Run Code Online (Sandbox Code Playgroud)

正确输出:

This desk belongs to Julia
This chair belongs to Sandra
This pen belongs to John
This book belongs to Paul
This lamp belongs to
Run Code Online (Sandbox Code Playgroud)

什么不起作用:

现在,我想添加一个条件,因为最后一个thing可能没有owner。模板将如下所示:

{{#each things}}
    {{#if lookup ../owners @index}}
        <p>This {{this}} belongs to {{lookup ../owners @index}}</p>
    {{else}}
        <p>...But this {{this}} belongs to nobody</p>
    {{/if}}
{{/each}}
Run Code Online (Sandbox Code Playgroud)

输出:

This desk belongs to Julia
This chair belongs to Sandra
This pen belongs to John
This book belongs to Paul
...But this lamp belongs to nobody
Run Code Online (Sandbox Code Playgroud)

不幸的是,这{{#if lookup ../owners @index}}东西行不通。

我的问题:是否可以使用内置的Handlebars帮助器实现此目的,还是必须编写自定义帮助器?

小智 5

实际上,您可以使用子表达式执行您想做的事情:

{{#if (lookup ../owners @index)}}

奇迹般有效。(来源:Handlebars网站