Flask by Example: Static Asset Loading
Web applications need to serve static files like CSS, JavaScript, and images. Flask provides a dedicated `static` folder and the `url_for` function to generate correct URLs for these assets.
Code
<!-- Directory Structure:
/app.py
/static
/css
style.css
/js
main.js
/img
logo.png
/templates
index.html
-->
<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
<!-- 1. Linking CSS -->
<link rel="stylesheet"
href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
<!-- 2. Displaying Images -->
<img src="{{ url_for('static', filename='img/logo.png') }}"
alt="Logo">
<h1>Welcome</h1>
<!-- 3. Linking JavaScript -->
<script src="{{ url_for('static', filename='js/main.js') }}"></script>
<!-- 4. Favicon -->
<link rel="shortcut icon"
href="{{ url_for('static', filename='favicon.ico') }}">
</body>
</html>Explanation
Flask automatically serves files from the static folder at the root of your application. This is where you should place your CSS, JavaScript, and image files to keep them separate from your code.
You should always use url_for('static', filename='...') to generate URLs for these assets. This ensures that the URLs are correct regardless of where your application is deployed or if it's running under a subdirectory.
Hardcoding paths like /static/style.css should be avoided. Using url_for maintains portability and allows for future optimizations, such as cache busting or serving assets from a CDN.
Code Breakdown
url_for('static', ...). The first argument 'static' refers to the endpoint name that Flask automatically creates for the static folder.filename='css/style.css'. The filename is relative to the static folder. You can organize your static folder with subdirectories like css, js, and img.<img src="...">. The generated URL will look like /static/img/logo.png (on a local dev server).
