Variable in Flask static files routing [url_for('static', filename='')]
15,238
Solution 1
I don't believe you can nest template tags like that. But you also shouldn't need to.
<img src="{{ url_for('static', filename='uploads/users/') }}{{ song['artistName'] }}/{{ song['pathToCover'] }}">
You can see why this works from the following example:
>>> from flask import Flask, url_for
>>> app = Flask(__name__)
>>> with app.test_request_context():
... print url_for('static', filename='uploads/users/')
/static/uploads/users/
So then you just need to add the artistName
, /
, pathToCover
Solution 2
I think you can do
<img src="{{ url_for('static', filename='uploads/users/'+ song['artistName']+'/'+ song['pathToCover'])}}">
It works for me :)
Related videos on Youtube
Comments
-
Nodari Lipartiya almost 2 years
I'm making a simple music app. I want to allow users upload their audio files and I have a page where I'm planning to show all songs. I've created a template, and the structure looks like:
{% for song in songs %} <div class="chart-item"> <div class="chart-position col-md-1"> <h3>#u</h3> </div> <!-- chart-position --> <div class="band-logo col-md-2"> <img src="{{ url_for('static', filename='uploads/users/{{ song['artistName'] }}/{{ song['pathToCover'] }}')}}"> </div> <!-- band-logo --> <div class="band-name-and-autio col-md-9"> <div class="band-name">{{ song['artistName'] }} - {{ song['songName'] }}</div> <!-- band-name --> <div class="audio"> <audio> </audio> </div> <!-- audio --> </div> <!-- band-name-and-autio --> <div class="clearfix"></div> </div> <!-- chart-item --> {% endfor %}
Here I want to make a dynamical path to cover image and a record, but I do not know to correctly write the path to the file here:
<img src="{{ url_for('static', filename='uploads/users/{{ song['artistName'] }}/{{ song['pathToCover'] }}')}}">
Please, explain how to do it. I've tried to find the solution on flask web page, but for now I have no any result.
-
Nodari Lipartiya over 10 yearsI do not think, that I understand your answer, but it gave me an idea. Here is my code : <pre><img src="{{ url_for('static', filename='uploads/users/') }}{{ song['artistName']}}/{{ song['pathToCover'] }} "></pre>
-
aychedee over 10 yearsYup, as I said in my answer, stop nesting template tags. Just run them into each other instead.
-
Nodari Lipartiya over 10 yearsThanks, you really helped me
-
aychedee over 10 yearsNo problem! If an answer solves you problem you should accept it as well.
-
Nodari Lipartiya over 9 yearsA year has gone, but I've made it. I accept your answer=)
-
aychedee over 9 yearsThanks Nodarl :) I'm glad you've made it through another year.
-
Tri over 4 yearsThis works for me :)
<img src="{{ url_for('static', filename='images/app/'+data['image']) }}" alt="{{data.image}}">
Thanks @Bones and Teeth