我有以下数据结构:
{ things: [ "desk", "chair", "pen", "book", "lamp" ], owners: [ "Julia", "Sandra", "John", "Paul" ] }
工作原理:
此handleblars
模板:
{{#each things}}This {{this}} belongs to {{lookup ../owners @index}}
{{/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}}This {{this}} belongs to {{lookup ../owners @index}}
{{else}}...But this {{this}} belongs to nobody
{{/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网站)