Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 645
aw crud Avatar asked Sep 23 '11 15:09

aw crud


1 Answers

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}}
    
like image 165
Andreas Andreou Avatar answered Nov 19 '22 12:11

Andreas Andreou