Boaz Hoch
Boaz Hoch

Reputation: 1229

Handlebars how to get sibling value inside an object

ok so iv got an object which looks like this:

Magnetim.photos = {
 facebook:{albums: {id:["id1","id2","id3","id4"] , albumName:["n1","n2","n3","n4"]}},
}

inside a handlebars template im doing this line of code:

<select id="albums-selection">
  {{#each photos.facebook.albums.albumName}}
    <option id="{{photos.facebook.albums.id}}" value="{{this}}">{{this}}</option>
 {{/each}}
</select>

this outputs this result:

<option id="id1,id2,id3,id4" value="n1">n1</option>
<option id="id1,id2,id3,id4" value="n2">n2</option>
<option id="id1,id2,id3,id4" value="n4">n3</option>
<option id="id1,id2,id3,id4" value="n4">n4</option>

but what i'm trying to achieve is for every name set the id element to its own id, so it looks like this:

<option id="id1" value="n1">n1</option>
<option id="id2" value="n2">n2</option>

etc..

Upvotes: 1

Views: 1235

Answers (1)

Igor Milla
Igor Milla

Reputation: 2786

While you are in the {{#each}} statement handlebars provides you with @index variable to track the current item index. Knowing this, you should be able to get corresponding item from other array.

So first you need to step outside of your {{#each}}, this is done by using ../, which will move you one level up.

My initial aproach was simply to do something like this

{{../albumName.[@index]}}

But for some reason that didn't work out. So I wrote the helper to simply grab item from array by index you pass there:

Handlebars.registerHelper('getAlbumName', function(array, id) {
        return array[id];
    });

Now your handlebars template will look like this:

  <script id="template">
        <select id="albums-selection">
            {{#each id}}           
              <option id="{{this}}" value="{{getAlbumName ../albumName @index}}">
                {{getAlbumName ../albumName @index}}
              </option>
            {{/each}}
        </select>
    </script>

    <div id="output"></div>

And here is the js:

var Magnetim = {};
Magnetim.photos = {
    facebook: {
        albums: {
            id: ["id1", "id2", "id3", "id4"],
            albumName: ["n1", "n2", "n3", "n4"]
        }
    }
};

var source = $("#template").html();
var template = Handlebars.compile(source);

Handlebars.registerHelper('getAlbumName', function(albums, id) {
    return albums[id];
});

$("#output").html(template(Magnetim.photos.facebook.albums));

Final jsfiddle with everything in place

Upvotes: 2

Related Questions