Dynamic search for steering elements in each cycle

In Handlebars 2+, how do I dynamically read a property in a loop like this? objects is an array of objects. keys is an array of strings. I want to loop each key for each object and put its .foo value in a span .

 {{#each objects}} {{#each keys}} <span>{{../this.{{this}}.foo}}</span> {{/each}} {{/each}} 

Is this possible in simple 2+ pens? Or ... is there a helper that does this?

+6
source share
3 answers

I do not see how this can be done without an assistant.
With helpers, anything is possible (but kind of ugly) in Handlebars.

For example, you can use something like this:

 {{#each objects}} {{#each keys}} <span>{{lookupProp ../this this 'foo'}}</span> {{/each}} {{/each}} 

And assistant:

 Handlebars.registerHelper('lookupProp', function (obj, key, prop) { return obj[key] && obj[key][prop]; }); 

Take a look at the fiddle .

Pens have a built-in lookup helper from version 3.0.3.

+7
source

Well ... spent a few hours searching and found a good solution, since I had the same problem, but could not find ...

I was as happy as Larry, and jumped off the chair when I finally figured out how to do it: D

This way you can access objects using dynamic keys ,

Sample Object:

 var categories = { onion: { name: 'bar', id: 4 }, apple: { name: 'demo', id: 2 }, carrot: { name: 'foo', id: 3 }, Root: [ { name: 'apple' }, { name: 'onion' }, { name: 'carrot' } ] }; 

Instead of trying something like this: (that won't work)

 {{#each categories.[@key]}} or {{#each categories.[mykey]}} 

You can do:

 {{#each categories.[Root] as |main-category|}} {{#each (lookup ../categories main-category.name) as |sub-category|}} {{sub-category.name}} {{/each}} {{/each}} 

Hope this helps someone else too :)

+1
source

For those who do not want to use a loop, you can use with for example.

 {{#with (lookup myObject myKeyVar) as |subObject|}} {{subObject.key}} {{/with}} 
+1
source

Source: https://habr.com/ru/post/986185/


All Articles