Scott
Scott

Reputation: 1310

Can handlebars access unique object names in a loop?

I'm returning a 3rd party object to handlebars but i've noticed that some property names are prefixed with unique namespaces. Here's a short extract:

var data={
    "soapenv:Envelope":{

      "soapenv:Body":{

           "CaseDetails":[
            {
             "Status":"Open",
             "Opened":"2018-02-19T10:56:03.783Z",
             "ns1:CaseReference": {"id":"111111"}
            },
            {
             "Status":"Closed",
             "Opened":"2017-02-19T10:56:03.783Z",
             "ns3:CaseReference": {"id":"222222"}
            },
            {
             "Status":"Closed",
             "Opened":"2016-02-19T10:56:03.783Z",
             "ns8:CaseReference": {"id":"3333"}
            }
            ]
      }

    }
};

I want to loop through this object and output the information. Is it possible to match these unique names: ns1:CaseReference, ns3:CaseReference and ns8:CaseReference?

{{#each data.soapenv:Envelope.soapenv:Body.CaseDetails}} 

<td>{{Status}}</td>
<td>{{Opened}}</td>
<td>{{???.id}}</td>

{{/each}} 

Upvotes: 1

Views: 762

Answers (2)

Gibin Ealias
Gibin Ealias

Reputation: 2859

You can write a custom HandlebarsHelper, ifKeyHasText to check whether the key contains a specific string (CaseReference in this scenario).

Handlebars.registerHelper('ifKeyHasText', function(array, value, options) {

  var key;

  if(Object.keys(array).some(function(k){
    if(~k.indexOf(value)){
      key = k;
    }
  }));

  if(key){
    return options.fn(this[key]);
  }

});

And in the template, you can pass the string CaseReference to the helper {{#ifKeyHasText}} along with the data JSON as this object.

{{#each soapenv:Envelope.soapenv:Body.CaseDetails}} 
  <td>{{Status}}</td>
  <td>{{Opened}}</td>
  <td>
    {{#ifKeyHasText this 'CaseReference'}}
      {{id}}
    {{/ifKeyHasText}}
  </td>
{{/each}}

Hope this helps.

Upvotes: 1

Scott
Scott

Reputation: 1310

I managed to get it based on this post: https://stackoverflow.com/a/21452230/1622376

var data={

"soapenv:Envelope":{

  "soapenv:Body":{

       "CaseDetails":[
        {
         "Status":"Open",
         "Opened":"2018-02-19T10:56:03.783Z",
         "ns1:CaseReference": {"id":"111111"}
        },
        {
         "Status":"Closed",
         "Opened":"2017-02-19T10:56:03.783Z",
         "ns3:CaseReference": {"id":"222222"}
        },
        {
         "Status":"Closed",
         "Opened":"2016-02-19T10:56:03.783Z",
         "ns8:CaseReference": {"id":"3333"}
        }
        ]
  }

}

};

Handlebar using 'this' to traverse the tree:

<ul>
{{#each soapenv:Envelope}}
    {{#each this}}
        {{#each this}}
            <li>
            {{this.Status}}
            {{#each this}}            
                {{this.id}}
            {{/each}}
            {{this.Opened}}
            </li>
        {{/each}}
    {{/each}}
{{/each}}
</ul>

Upvotes: 1

Related Questions