简体   繁体   中英

Does Handlebars.js allow for dynamic templates?

I have started to play around with the Spotify API as a personal learning exercise and started with the beginners tutorial.

The example code given uses handlebars.js for templates and I actually think its pretty cool. how ever I can't figure out a way to do what I want to accomplish.

This is my template

<script id="recently-played-template" type="text/x-handlebars-template">

    <div class="">
      <dl class="dl-horizontal">
        <h3> Recently Played </h3>

    <p>{{items.0.track.artists.0.name}} - {{items.0.track.name}}</p> 

      </dl>
    </div>
  </div>
</script> 

I am doing the following call to the spotify API. Upon success it will fill the template with that JSON response data which then gets put in a placeholder div to display the data to the user

        $.ajax({
            url: 'https://api.spotify.com/v1/me/player/recently-played',
            headers: {
              'Authorization': 'Bearer ' + access_token
            },
            success: function(response) {
              recentlyPlayedPlaceholder.innerHTML = recentlyPlayedTemplate(response);


              $('#login').hide();
              $('#loggedin').show();
            }
        });

SO what I am trying to figure out how to do is to build my template in a way that based on how many tracks are returned.

Lets say a user hasn't used spotify in a week and then listens to 3 songs. then I want 3 songs displayed.

if they listened to 10 I want 10 displayed.

I just am not sure how to make the template dynamic.

I don't need the straight answer just a push in the right direction.any help is apprecaited.

I assume that your code is working without any error. Remove <p>{{items.0.track.artists.0.name}} - {{items.0.track.name}}</p> and try the code below.

  {{#each items}}
    <li>{{track.name}}</li>
  {{/each}}

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