0

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.

TonyO
  • 199
  • 1
  • 14
  • Nothing says you have to do this in a _single_ template expansion - maybe you have to expand a per-track template for each track, concatenate those, and then put the result into a template for the full div contents? – DisappointedByUnaccountableMod Mar 13 '17 at 14:52

1 Answers1

1

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}}
A.Onur Özcan
  • 143
  • 2
  • 10
  • works perfect. Can you tell me how that works? is that something specific to handlebars.js? – TonyO Mar 13 '17 at 15:02
  • I think I understand now. it is a for each loop that executes for amount of 'items' in the JSON response. I just don't quite understand the syntax. I haven't seen #each and /each before. – TonyO Mar 13 '17 at 15:47
  • Yes, you're right. It is something specific to handlebars. It works like a for each loop. For further information you can check out this link [Handlebars Built-in Helpers](http://handlebarsjs.com/builtin_helpers.html) – A.Onur Özcan Mar 13 '17 at 18:11