简体   繁体   中英

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM