Search code examples
pythonflaskjinja2spotifyspotipy

How can I call a Python module inside a Jinja for loop?


I have this function in Flask where I do a search on spotify:

@app.route('/search', methods=['GET','POST'])
def search():
    data = sp.search(request.form['code'])
    api_url = data['tracks']['href']
    items = data['tracks']['items']
    for item in items:
        artist = sp.artist(item['artists'][0]['uri'])
        image_url = artist['images'][2]['url']
    html = render_template('search.html',
                            artist_name=request.form['code'],
                            results=items,
                            api_url=api_url,
                            image_url=image_url)
    return html

This is the Jinja template in my html page:

{% for artist in results %}
        <tr>
          <td>
            <img src="{{image_url}}" alt="{{image_url}}" class="bobby img-thumbnail img-circle">
            <a href="{{ url_for('artist', id=artist.id) }}">
              {{ artist.name }}
            </a>
          </td>
          <td>
            {{ artist.artists.0.name }}
          </td>
        </tr>
      {% endfor %}

I correctly recieve the artist and song. But I have a problem with the part where I try to recieve the picture for every artist:

for item in items:
  artist = sp.artist(item['artists'][0]['uri'])
  image_url = artist['images'][2]['url']

I get the same picture for all the artists. Should that for loop with the spotipy module be inside the Jinja template? And how can I do that?


Solution

  • Update search function first:

    @app.route('/search', methods=['GET','POST'])
    def search():
        data = sp.search(request.form['code'])
        api_url = data['tracks']['href']
        items = data['tracks']['items']
        for item in items:
            artist = sp.artist(item['artists'][0]['uri'])
            item['image_url'] = artist['images'][2]['url'] # <-- change this line
        html = render_template('search.html',
                                artist_name=request.form['code'],
                                results=items,
                                api_url=api_url,
                                image_url=image_url)
        return html
    

    Then you need to update your template

    <img src="{{artist.image_url}}" alt="{{artist.image_url}}" class="bobby img-thumbnail img-circle">