把手:使用儿童财产访问家长的JSON属性 [英] Handlebars: Accessing JSON Property of Parent using child property
问题描述
数据:
{
games:[game:{teamID:1}]
teams:{1:{name:'Team Name'}}
)
模板(注意在> {{#each games }}
:
{{#teamFetch ../这个teamID'name'}} {{ / teamFetch}}
助手:
Handlebars.registerHelper('teamFetch',function(season,teamid,property){
return season.teams [teamid] [property];
});
我是新来的把手,但这是我唯一可以找出如何访问特定团队的方法这个季节基于游戏中的id,并获得该团队的一个属性。是否有一种更简单的方法,不需要辅助函数?
没有办法避开不使用帮手他的是因为Handlebars不允许你在他们的段文字符号中传递一个变量来指定变量路径。在表达式的把手文件中:
要引用不是有效标识符的属性,您可以使用分段字面符号:{{#each articles。[10] .comments}} {{/ each}}
所以......理想情况下,我们希望能够做到这样的事情:
<$ p $
{{#each games}}
{{../teams.[teamID].name}}
{{/ each}}
但现在,无法传递 teamID $ c $的值c>转换为
../ teams。[] .name
。
只能这样做:
{{#each games}}
{{../teams.[0].name}}
$ b 它只能解释数值,例如。 0
,并且无法解析变量,例如。 teamID
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?
解决方案 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
这篇关于把手:使用儿童财产访问家长的JSON属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!