Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handlebars.js - Access object value with a variable key

Tags:

Looking for a way to access to achieve this:

{{#each someArray}}   {{../otherObject.[this]}} {{/each}} 

How do I evaluate the value of this and then reference it as a key to my object otherObject?

like image 494
Kevin Wang Avatar asked Oct 28 '13 22:10

Kevin Wang


People also ask

How do you access the properties of an object with a variable?

Answer: Use the Square Bracket ( [] ) Notation There are two ways to access or get the value of a property from an object — the dot ( . ) notation, like obj. foo , and the square bracket ( [] ) notation, like obj[foo] .

Can you use JavaScript in handlebars?

Handlebars compiles templates into JavaScript functions. This makes the template execution faster than most other template engines.

What is helper in Handlebars?

A Handlebars helper call is a simple identifier, followed by zero or more parameters (separated by a space). Each parameter is a Handlebars expression that is evaluated exactly the same way as described above in "Basic Usage": template {{firstname}} {{loud lastname}}


2 Answers

With lookup: https://handlebarsjs.com/guide/builtin-helpers.html#lookup

{{#each someArray}}   {{lookup ../otherObject this}} {{/each}} 
like image 109
Mario Negrete Avatar answered Sep 18 '22 13:09

Mario Negrete


One possible solution with a helper:

/* {{#each someArrayOfKeys}}   {{#withItem ../otherObject key=this}}     {{this}}   {{/withItem}} {{/each}} */  Handlebars.registerHelper('withItem', function(object, options) {     return options.fn(object[options.hash.key]); }); 
like image 36
Fabricio c Zuardi Avatar answered Sep 18 '22 13:09

Fabricio c Zuardi