是否有任何方法可以在我的Mustache.js模板中的嵌套结构中绕过名称冲突

Is there any way to get around name collisions in nested structures in my Mustache.js templates?

本文关键字:结构 嵌套 冲突 方法 任何 js Mustache 我的 是否      更新时间:2023-09-26

我真的有名字冲突的问题在我的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
  1. 在嵌套的{{#childRecs}}块中没有办法访问父{{#recs}}{id}}{{/recs}}字段——它被{{#childRecs}}{{id}}{{/childRecs}}

  2. 覆盖
  3. 如果{{#childRecs}}中缺少一个变量,并且存在同名的父变量,则无法阻止它打印父变量

我的嵌套结构非常深,并且有许多名称冲突,因此以不冲突的方式重命名它们是不可行的选择。还有别的办法解决我的问题吗?

我看到两个选项:

  • 在发送数据进行呈现之前,在客户端丰富数据。例如,你可以遍历所有的childRecs并添加一个新的parentId属性——然后更新或者

  • 使用http://www.handlebarsjs.com/-它保持胡子语法,但增加了一些好处,如访问父上下文(通过../)。例如:

    {{#recs}}
        Record ID: {{id}}
        {{#childRecs}}
            This child code is: [{{code}}] and its parent ID is: {{../id}}
        {{/childRecs}}
    {{/recs}}