aw crud
aw crud

Reputation: 8891

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

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
  1. 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}}

  2. 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?

Upvotes: 6

Views: 2971

Answers (1)

Andreas Andreou
Andreas Andreou

Reputation: 1332

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}}
    

Upvotes: 7

Related Questions