我有以下JSON数据集,并希望遍历users
并为他们可以访问的每个apps
呈现链接。我已成功遍历用户数组,并从每个用户包含的应用程序数组中呈现每个应用程序的名称。但是,我不知道如何从apps数组中查找应用程序URL。这可以在Handlebars.js模板中完成吗?
{ "config": {
"users":
[
{
"name": "Bob Jones",
"title": "Developer",
"apps": ["app1","app2","app4"]
},
{
"name": "Brad Willis",
"title": "Manager",
"apps": ["app2","app4"]
}
],
"apps":
[
{
"name": "app1",
"url": "http://host/app1"
},
{
"name": "app1",
"url": "http://host/app1"
},
{
"name": "app1",
"url": "http://host/app1"
},
{
"name": "app1",
"url": "http://host/app1"
}
]
}
}
以下是我目前用于显示用户和应用的模板:
{{#each config.users}}
<div class="user-panel">
<div class="user-panel-name">{{this.name}}</div>
<div class="user-panel-title">{{this.title}}</div>
<div class="user-panel-apps">
{{#each this.apps}}
<a class="btn btn-success btn-sm" onclick="DoLogin('APP URL GOES HERE');">{{this.name}}</a>
{{/each}}
</div>
</div>
{{/each}}
答案 0 :(得分:0)
{{#each this.apps}}
<a class="btn btn-success btn-sm" onclick="DoLogin('{{this.url}}');">{{this.name}}</a>
{{/each}}
&#13;
答案 1 :(得分:0)
注册helper
以获取特定应用的网址。
模板:
{{#each config.users}}
<div class="user-panel">
<div class="user-panel-name">{{this.name}}</div>
<div class="user-panel-title">{{this.title}}</div>
<div class="user-panel-apps">
{{#each this.apps}}
<a class="btn btn-success btn-sm" onclick="DoLogin('{{url this}}');">{{this}}</a>
^^^^^^^^
{{/each}}
</div>
</div>
{{/each}}
脚本:
var val = {
"config": {
"users": [
{
"name": "Bob Jones",
"title": "Developer",
"apps": ["app1", "app2", "app4"]
},
{
"name": "Brad Willis",
"title": "Manager",
"apps": ["app2", "app4"]
}
],
"apps": [
{
"name": "app1",
"url": "http://host/app1"
},
{
"name": "app1",
"url": "http://host/app1"
},
{
"name": "app1",
"url": "http://host/app1"
},
{
"name": "app1",
"url": "http://host/app1"
}
]
}
};
Handlebars.registerHelper('url', function (app) {
for (var i = 0, len = val.config.apps.length; i < len; i++) {
if (app == val.config.apps[i].name) {
return val.config.apps[i].url;
}
}
});