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?
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:
{{#recs}}
Record ID: {{id}}
{{#childRecs}}
This child code is: [{{code}}] and its parent ID is: {{../id}}
{{/childRecs}}
{{/recs}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With