Philippe Sabourin
Philippe Sabourin

Reputation: 8075

Handlebars: Accessing JSON Property of Parent using child property

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?

Upvotes: 1

Views: 1718

Answers (1)

Amy
Amy

Reputation: 7496

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

Upvotes: 4

Related Questions