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

I really have problems with name conflicts in my Mustache templates (using Mustache.js). This example illustrates these two problems:

I pass this data:

{'recs': {'code': 'foo', 'id': 1 'childRecs': [{'id': 2}, {'code': 'bar', 'id': 3}] } } 

In 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 
  • In the nested block {{#childRecs}} there is no access to the parent field {{#recs}}{id}}{{/recs}} - it is overwritten {{#childRecs}}{{id}}{{/childRecs}}

  • If there is no variable in {{#childRecs}} and a parent variable with the same name exists, there is no way to prevent the parent variable from printing.

My nested structures are very deep and there are many name conflicts, 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?

+6
source share
1 answer

I see two options:

  • Enrich client-side data before submitting for rendering. For example, you can iterate over all child replicas and add a new parentId property, and then update your template accordingly, or

  • Use http://www.handlebarsjs.com/ - it preserves the mustache syntax, but adds some useful properties, such as access to the parent context (via ../ ). For instance:

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

Source: https://habr.com/ru/post/897910/


All Articles