We use url_for to get the correct web address for static files like images or stylesheets. This helps keep links working even if the file location changes.
0
0
URL_for with static files in Flask
Introduction
You want to add an image to your webpage from the static folder.
You need to link a CSS file stored in your static directory.
You want to include a JavaScript file from your static files.
You want to avoid hardcoding file paths to static resources.
You want Flask to handle the correct URL for static content automatically.
Syntax
Flask
url_for('static', filename='path/to/file.ext')
The first argument is always the string 'static' to tell Flask you want a static file.
The filename argument is the path inside the static folder.
Examples
Gets the URL for
static/style.css.Flask
url_for('static', filename='style.css')
Gets the URL for an image inside a subfolder
images.Flask
url_for('static', filename='images/logo.png')
Gets the URL for a JavaScript file inside
js folder.Flask
url_for('static', filename='js/app.js')
Sample Program
This Flask app creates a homepage that links to a CSS file stored in the static folder using url_for. This way, the link to the CSS file is always correct.
Flask
from flask import Flask, url_for app = Flask(__name__) @app.route('/') def home(): # Get URL for a CSS file in static folder css_url = url_for('static', filename='style.css') # Return simple HTML using that URL return f"<link rel='stylesheet' href='{css_url}'>\n<p>Hello with styled page!</p>" if __name__ == '__main__': app.run(debug=True)
OutputSuccess
Important Notes
Flask automatically serves files from the static folder at the URL path /static/.
Using url_for avoids hardcoding URLs, which helps when deploying or changing folder structures.
Remember to place your static files inside the static directory in your Flask project.
Summary
url_for helps get the correct URL for static files in Flask.
Always use url_for('static', filename='...') to link static resources.
This keeps your app flexible and avoids broken links.