我正在使用Handlebars模板。如果我想在hbs文件中插入变量,我将其添加为{{var_name}}
。
问题是,我有一个大对象,其键的格式类似于:
{
"stats.name":"John",
"stats.performance.day":123,
"stats.performance.month":4567,
"company":"My LLC"
}
如果我尝试将这些作为{{company}}, {{stats.name}}, {{stats.performance.day}}, {{stats.performance.month}}
添加到Handlebars文件中,则只会显示{{company}}
。所有其他值都是空白的,我假设是因为“。”是Handlebars中的一个特殊角色。
我的问题是,有没有办法覆盖它,或者我是否真的需要迭代这个对象并更改每个“。”在将它传递给Handlebars之前使用“_”或其他东西使其起作用?
答案 0 :(得分:1)
我建议您重命名您的属性。 Dot Notation是在JavaScript中访问对象属性的两种方法之一。典型代码如下:obj.prop
。如果您的对象的密钥不有效identifiers,那么您必须使用Bracket Notation:obj['my-prop']
。由于点是属性访问器,因此在属性名称中看到一个非常罕见。如果我遇到编写为obj['stats.performance.date']
的代码,我会认为这是一个错误,obj.stats.performance.date
是有意的。
据说,Handlebars 支持引用非有效标识符的属性。这称为"segment-literal-notation",就像在标识符周围包围方括号一样简单:
{{[stats.performance.day]}}
文档还说明:
JavaScript样式字符串“和”也可用于[pair。
因此以下备选方案有效:
{{"stats.performance.day"}}
{{'stats.performance.day'}}