Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable is undefined inside 'each' in Handlebars.js

I have my render function:

renderTracksList = function(tracks){
    var source   = $("#timeline-template").html();
    var template = Handlebars.compile(source);
    var data     = {
                    tracks: tracks, 
                    client_id: App.config.client_id
                };

    var html     = template(data);

    $('#timeline').html(html);
}

And in my template I'm trying to use print client_id inside the loop, but in the loop context it's undefined, so how to access and print the variable?

{{#each tracks}}
<div class="track">
    {{title}} - 
    <a href="javascript:App.play('{{permalink_url}}')">PLAY</a>
    {{#if downloadable}}
    - <a href="{{download_url}}?client_id={{client_id}}" target="_blank">DOWNLOAD</a>
    {{/if}}
</div>
{{/each}}

Btw, I've already tried this:

<a href="{{download_url}}?client_id={{../client_id}}" target="_blank">DOWNLOAD</a>
like image 906
Rafael Santos Sá Avatar asked Apr 01 '13 20:04

Rafael Santos Sá


1 Answers

Try to repeat ../ for both the {{#if}} and the {{#each}}:

<a href="{{download_url}}?client_id={{../../client_id}}" target="_blank">DOWNLOAD</a>

Even though {{#if}} keeps the value of the previous context, it still creates another entry in the stack that ../ steps back through.

like image 56
Jonathan Lonowski Avatar answered Nov 14 '22 23:11

Jonathan Lonowski