Handlebars路径使用@key:筛选符合条件的method问题
筛选符合条件的method项
数据结构
{ method: ['twitter','reddit','google'], auth: { twitter: {id: 213}, reddit: {}, } }
需求
需要筛选出两类method:
- 不在auth对象中的项
- 在auth对象中但未定义id的项
预期输出:
- 带id的auth项:twitter
- 符合筛选条件的项:reddit、google
现有代码问题
当前代码第二部分只能识别不在auth里的google,无法识别auth中无id的reddit:
methods in auth with id: {{#each auth}} {{#if id}} {{@key}} {{/if}} {{/each}} methods not in auth with id: {{#each method}} {{#unless (lookup ../auth this)}} {{this}} {{/unless}} {{/each}}
修复方案
修改第二部分的判断逻辑,同时检查“条目不存在”或“条目存在但无id”两个条件:
methods not in auth with id: {{#each method}} {{#or (not (lookup ../auth this)) (not (lookup ../auth this).id)}} {{this}} {{/or}} {{/each}}
如果想要更清晰的变量复用,可以用let助手暂存auth条目:
{{#each method}} {{#let authEntry=(lookup ../auth this)}} {{#or (not authEntry) (not authEntry.id)}} {{this}} {{/or}} {{/let}} {{/each}}
逻辑说明:
lookup ../auth this获取当前method对应的auth对象条目(not authEntry)判断该条目是否不存在(对应google的情况)(not authEntry.id)判断条目存在但没有id属性(对应reddit的情况)or助手只要满足其中一个条件,就输出当前method
内容的提问来源于stack exchange,提问作者stackers
相关产品推荐
相关产品推荐

