Handlebars retrieve object value in which the key will be present in another object

  handlebars.js, javascript, json

There will be 2 json, one will contain the constant json other will have the original values. Consider this for eg,

{
  constant : {address: "location"},
  data : {location : "india"}
}

constant and data are the two json object.

<div class="entry">
  <div class="body">
     {{data.[constant.address]}}
  </div>
</div>

It is not retrieving the expected value ‘india’. {{constant.address}} is returing ‘location’ and {{data.location}} is returning ‘india’. I am not sure about this behaviour, any explanation about this behaviour is really helpful. Anyhow i can achieve this with the help of below helper function.

Handlebars.registerHelper('getKey', function(object, key){
    return object[key];
});

In handlebars,

<div class="entry">
  <div class="body">
     {{getKey data constant.address}}
  </div>
</div>

Here, ‘india’ is getting printed.
Thanks in advance.

Source: Ask Javascript Questions

LEAVE A COMMENT