把手条件基于查找

时间:2015-12-27 18:58:06

标签: javascript handlebars.js

我有以下数据结构:

{
    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助手实现这一目标,还是必须编写自定义助手?

4 个答案:

答案 0 :(得分:3)

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

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

就像魅力一样。 (来源:Handlebars website

答案 1 :(得分:1)

我认为如果要更改数据结构会更好,例如:

[
        {   
            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>

使用把手助手可能看起来不错,但从长度来看,从把手移动到javascript 的逻辑会更好。

答案 2 :(得分:0)

我相信答案是“不”。如果你想用lookup嵌套Handlebars if

但是在这里,如果您想省略不具有thing的最后owner(或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>

希望这有帮助。

答案 3 :(得分:0)

我通过编写自定义帮助程序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}}

希望这有帮助。