Cannot Show Image From Static_folder In Flask Template

Solution 1:
I'm not sure what is this STATIC_FOLDER
configuration item you are using. Where did you find it?
There are actually two arguments to the Flask
class constructor that govern the configuration of static files:
static_folder: defaults to "static". This is the prefix that you have to use in URLs to access the static files.
static_url_path: this is the disk location of the static folder. By default this value is the same as the static_folder setting.
For example, if you use this configuration:
from flask importFlaskapp= Flask(__name__, static_url_path = "/tmp", static_folder = "tmp")
Then you can access your images as follows:
<imgsrc='/tmp/IKE2low.jpg'width="200"height="85">
You can also remove the need to have a prefix in the URLs as follows:
from flask importFlaskapp= Flask(__name__, static_url_path = "", static_folder = "tmp")
And then you can access your images as:
<imgsrc='/IKE2low.jpg'width="200"height="85">
Note that you still need to have a root /
.
But the best way to do this is to not reference image paths explicitly and instead use url_for
to generate the correct URLs. If you are using Jinja2 templates that would be:
<imgsrc="{{ url_for('static', filename = 'IKE2low.jpg') }}"width="200"height="85">
This last expression would work regardless of where and how the static files are configured.
Post a Comment for "Cannot Show Image From Static_folder In Flask Template"