Reputation: 14096
I'm using url_for
to generate my images url.
<img src="{{ url_for('static', filename='imgs/' + images[id]) }}" >
How to make url_for
return /static/imgs/default.jpg
when the requested image does not exist on the server ?
Upvotes: 0
Views: 1350
Reputation: 12762
You can use onerror
attribute:
<img src="{{ url_for('static', filename='imgs/' + images[id]) }}" onerror="this.src='/static/imgs/default.jpg'">
Or listen error
event for img
element with JavaScript (jQuery):
$('img').on("error", function() {
$(this).attr('src', '/static/imgs/default.jpg');
});
If you just want make it with Flask, you will need to create a custom view function to handle your images, for example (not test yet):
import os
from flask import send_from_directory
# ...
@app.route('/img/<path:filename>')
def get_image(filename):
static_path = os.path.join(app.root_path, 'static')
img_path = os.path.join(static_path, filename)
if not os.path.exists(img_path):
return send_from_directory(os.path.join(static_path, '/imgs/default.jpg'))
return send_from_directory(img_path)
Template code:
<img src="{{ url_for('get_image', filename='/static/imgs/' + images[id]) }}" >
In production, you may use web server like Nginx to serve images, in this case, you can use [try_files](http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files)
directive in Nginx:
location /static/imgs/ {
try_files $uri /static/imgs/default.jpg;
}
Upvotes: 1