基于查找的车把条件

Handlebars condition based on lookup

我有以下数据结构:

{
    things: [
        "desk",
        "chair",
        "pen",
        "book",
        "lamp"
    ],
    owners: [
        "Julia",
        "Sandra",
        "John",
        "Paul"
    ]
}

工作原理:

这个handleblars模板:

{{#each things}}
    <p>This {{this}} belongs to {{lookup ../owners @index}}</p>
{{/each}}

正确输出:

This desk belongs to Julia
This chair belongs to Sandra
This pen belongs to John
This book belongs to Paul
This lamp belongs to

什么不起作用:

现在,我想添加一个条件,因为最后一个 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}}

输出:

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

不幸的是,这个 {{#if lookup ../owners @index}} 不起作用。

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

我想如果你能改变你的数据结构会更好,比如像这样:

[
        {   
            thing:    "desk",
            owner: "Julia"
        },
        {   
            thing: "chair",
            owner:"Sandra"
        },
        {   
            thing:  "pen",
            owner:  "John"},
        {   
            thing:  "book",
            owner:  "Paul"},
        { 
            thing:  "lamp"
        }
]    

那么您的车把模板将类似于

{{#each this}}
  {{#if this.owner}}
    <p>This {{this.thing}} belongs to {{ this.owner}}</p>
{{else}}
 <p>...But this {{this.thing}} belongs to nobody</p>
{{/if}}
{{/each}}

这将输出(我 运行 它在 http://tryhandlebarsjs.com/ 上)

<p>This desk belongs to Julia</p>
<p>This chair belongs to Sandra</p>
<p>This pen belongs to John</p>
<p>This book belongs to Paul</p>
<p>...But this lamp belongs to nobody</p>

使用 handlebars helpers 对你来说可能不错,但是将逻辑从 handlebars 转移到 javascript will long 运行.

如果您想用 if 嵌套车把 lookup,我相信答案是 'no'。

但是在这里,如果你想省略最后一个没有ownerthing(或n个东西),你可以反向检查#each,如下所示,

{{#each owners}}
  <p>This {{lookup ../things @index}} belongs to {{this}}</p>
{{/each}}

哪个输出,

<p>This desk belongs to Julia</p>
<p>This chair belongs to Sandra</p>
<p>This pen belongs to John</p>
<p>This book belongs to Paul</p>

希望这对您有所帮助。

我通过编写自定义助手找到了替代解决方案,isIndexExist

Handlebars.registerHelper("isIndexExist", function(array, value, options) {
  return value < array.length ? options.fn(this) : options.inverse(this);
});

并且在模板中,你可以这样写,

{{#each things}}
  {{#isIndexExist ../owners @index}}
    <p>This {{this}} belongs to {{lookup ../owners @index}}</p>
  {{else}}
    <p>...But this {{this}} belongs to nobody</p>
  {{/isIndexExist}}
{{/each}}

希望对您有所帮助。

你确实可以做你想做的事,使用子表达式:

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

很有魅力。 (来源:Handlebars website