繁体   English   中英

基于查找的车把状况

[英]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帮助器来实现,还是必须编写自定义帮助器?

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

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

使用车把帮手对您来说看起来不错,但从长远来看,将逻辑从车把移到javascript 更好。

我相信,如果您想将Handlebars lookupif嵌套在一起,答案是“否”。

但在这里,如果你想省略最后的thing (或n东西),它不具有owner ,您可以反向检查#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}}

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM