首页 > 解决方案 > 使用 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}}

它们都没有真正起作用。请帮忙,提前谢谢!

标签: handlebars.jshandlebars.java

解决方案


你的尝试是如此接近。lookup

问题是 Handlebars 不允许您像使用(lookup guests itemIndex).guestprofile. 它只是不能以这种方式解析动态变量,这也是为什么必须使用查找guests.itemIndex.guestprofile而不是.

您错过的部分是您实际上需要两次查找 - 一次获取guestsat的元素,itemIndex第二次获取该guestprofile元素的元素。

您的模板需要成为:

{{#if (lookup (lookup guests itemIndex) 'guestprofile')}}
    do something
{{/if}}

我创建了一个小提琴供您参考。


推荐阅读