有什么方法可以解决 Mustache.js 模板中嵌套结构中的名称冲突吗?
我的 Mustache 模板(使用 Mustache.js)确实遇到了名称冲突问题。此示例说明了这两个问题:
我正在将此数据传递
{'recs': {'code': 'foo', 'id': 1
'childRecs': [{'id': 2},
{'code': 'bar', 'id': 3}]
}
}
到此模板:
{{#recs}}
Record ID: {{id}}
{{#childRecs}}
This child code is: [{{code}}] and its parent ID is: {{id}}
{{/childRecs}}
{{/recs}}
预期:
Record ID: 1
This child code is: [] and its parent ID is 1
This child code is: [bar] and its parent ID is 1
实际:
Record ID: 1
This child code is [foo] and its parent ID is 2
This child code is [bar] and its parent ID is 3
嵌套的
{{#childRecs}}
块中无法访问父级{{#recs}}{id}}{{/recs}}
字段 - 它被{{#childRecs}}{{id}}{{/childRecs} 覆盖}
如果
{{#childRecs}}
中的变量是缺少,以及同名的父变量 则无法阻止其打印父变量。
我的嵌套结构非常深,并且存在很多名称冲突,因此以不冲突的方式重命名它们并不是一个可行的选择。还有其他方法可以解决我的问题吗?
I'm really having problems with name collisions in my Mustache templates (using Mustache.js). This example illustrates those two problems:
I'm passing this data:
{'recs': {'code': 'foo', 'id': 1
'childRecs': [{'id': 2},
{'code': 'bar', 'id': 3}]
}
}
Into this template:
{{#recs}}
Record ID: {{id}}
{{#childRecs}}
This child code is: [{{code}}] and its parent ID is: {{id}}
{{/childRecs}}
{{/recs}}
Expected:
Record ID: 1
This child code is: [] and its parent ID is 1
This child code is: [bar] and its parent ID is 1
Actual:
Record ID: 1
This child code is [foo] and its parent ID is 2
This child code is [bar] and its parent ID is 3
There is no way in the nested
{{#childRecs}}
block to access the parent{{#recs}}{id}}{{/recs}}
field -- it is overwritten by the{{#childRecs}}{{id}}{{/childRecs}}
If a variable in
{{#childRecs}}
is missing, and a parent variable of the same name exists, there is no way to prevent it from printing the parent variable.
My nested structures are very deep and there are many name collisions, so renaming them in such a way that they do not collide is not a viable option. Is there any other way to solve my problems?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我看到两个选项:
在发送数据进行渲染之前丰富客户端的数据。例如,
您可以循环所有 childRecs 并添加新的 ParentId 属性 - 然后更新
相应地修改您的模板,或者
使用http://www.handlebarsjs.com/ - 它保留小胡子语法,但添加了一些好处,例如访问父上下文(通过
../
)。例如:<前><代码>{{#recs}}
记录 ID:{{id}}
{{#childRecs}}
该子代码为:[{{code}}],其父 ID 为:{{../id}}
{{/childRecs}}
{{/建议}}
I see two options:
Enrich the data on the client-side before sending it for rendering. For instance,
you can loop over all the childRecs and add a new parentId property - and then update
your template accordingly, or
Use http://www.handlebarsjs.com/ - it keeps the mustache syntax but adds a few goodies like accessing the parent context (through
../
). For instance: