Handlebars: Accessing JSON Property of Parent using child property

梦想的初衷 提交于 2019-12-24 12:19:42

问题


I was wondering if there is a way to simplify this handlebars template to not use a helper.

Data:

{
    games:[game: {teamID:1}]
    teams:{1:{name:'Team Name'}}
}

Template (note that is is within a {{#each games}}:

{{#teamFetch ../this teamID 'name'}}{{/teamFetch}}

Helper:

Handlebars.registerHelper('teamFetch', function(season, teamid, property){
    return season.teams[teamid][property];
});

I'm new to handlebars but this was the only way I could figure out how to access a specific team in the season based on the id within a game, and get a property of that team. Is there a simpler way that doesn't require a helper function?


回答1:


There isn't a way to get around not using a helper. This is because Handlebars doesn't allow you to pass a variable in their segment-literal notation for specifying variable paths. In the Handlebars documentation regarding Expressions:

To reference a property that is not a valid identifier, you can use segment-literal notation: {{#each articles.[10].comments}} {{/each}}

So...ideally, we want to be able to do something like this:

{{#each games}}
        {{../teams.[teamID].name}}
{{/each}}

But as of right now, there is no way to pass in the value of teamID into ../teams.[ ].name.

It is only capable of doing this:

{{#each games}}
        {{../teams.[0].name}}
{{/each}}

It can only interpret values, eg. 0, and unable to resolve variables eg. teamID



来源:https://stackoverflow.com/questions/15749097/handlebars-accessing-json-property-of-parent-using-child-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!