Wells
Wells

Reputation: 10979

python, flask, and jinja2: passing parameters to url_for

I have this:

{{ url_for('static', filename='css/main.min.css') }}

But I also have a timestamp in the template I would like to pass to prevent caching, like:

{{ url_for('static', filename='css/main.min.css?timestamp=g.timestamp') }}

Which obviously doesn't work. The HTML needs to end up reading:

href="css/main.min.css?timestamp= 1440133238"

Upvotes: 3

Views: 3128

Answers (1)

Matt Healy
Matt Healy

Reputation: 18531

You could use something like this snippet to override the url_for handler for static files.

Here's a working example:

app.py

from flask import Flask, render_template, request, url_for
import os

app = Flask(__name__)
app.debug=True

@app.context_processor
def override_url_for():
    return dict(url_for=dated_url_for)

def dated_url_for(endpoint, **values):
    if endpoint == 'static':
        filename = values.get('filename', None)
        if filename:
            file_path = os.path.join(app.root_path,
                                     endpoint, filename)
            values['q'] = int(os.stat(file_path).st_mtime)
    return url_for(endpoint, **values)

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(port=5000)

templates/index.html

<html>
<body>
<img src="{{ url_for('static', filename='20110307082700.jpg') }}" />
</body>
</html>

When the page is accessed, the following appears in the access log:

127.0.0.1 - - [21/Aug/2015 13:24:55] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [21/Aug/2015 13:24:55] "GET /static/20110307082700.jpg?q=1422512336 HTTP/1.1" 200 -

Upvotes: 5

Related Questions