handlebars.js - 使用 handlebars.js 访问 Json 对象列表中的元素
问题描述
"guests": [
{
"guestname": "john smith",
"is_active": false,
"guestheight": "175cm",
"guestprofile": "https://www.example.com"
},
{
"guestname": "david smart",
"is_active": false,
"guestheight": "175cm"
}
]
我想检查guestprofile是否存在。鉴于我目前有一个变量保存我们试图在此处访问的列表的索引,即itemIndex
. 所以基本上我试图if guests[itemIndex]["guestprofile"]
在 handlebars.js 上下文中查询。
如果我直接引用
{{#if guests.0.guestprofile}}
//do something
{{/if}}
它工作正常。但是,如果我用下面的 itemIndex 替换 0 ,一切都坏了......
{{#if guests.itemIndex.guestprofile}}
//do something
{{/if}}
目前我也尝试过
{{#if (lookup guests itemIndex).guestprofile}}
//do something
{{/if}}
{{#if guests[itemIndex].guestprofile }}
//do something
{{/if}}
它们都没有真正起作用。请帮忙,提前谢谢!
解决方案
你的尝试是如此接近。lookup
问题是 Handlebars 不允许您像使用(lookup guests itemIndex).guestprofile
. 它只是不能以这种方式解析动态变量,这也是为什么必须使用查找guests.itemIndex.guestprofile
而不是.
您错过的部分是您实际上需要两次查找 - 一次获取guests
at的元素,itemIndex
第二次获取该guestprofile
元素的元素。
您的模板需要成为:
{{#if (lookup (lookup guests itemIndex) 'guestprofile')}}
do something
{{/if}}
我创建了一个小提琴供您参考。
推荐阅读
- dpdk - DPDK testpmd 显示链接已关闭,即使它已启动
- python - 网络摄像头上的水印覆盖非常慢
- passport.js - 如何链接帐户nestjs passportjs?
- pagination - 如何在下一个js中实现无限滚动?
- html - 单击阅读更多vuejs时显示整个文本
- flutter - 在等待来自 moor 数据库的 Future 之后,“未处理的错误 Null 检查运算符用于空值”
- string - 如何在 Shell 脚本中为空格分隔字符串中的子字符串添加前缀
- java - Android Studio 4.2.1 不适用于“org.androidannotations:androidannotations-api:4.8.0”
- sql - 在多对多表中查询 AND
- javascript - 如何布局此 CSS 网格模板