0
0
Flaskframework~5 mins

Static file organization in Flask

Choose your learning style9 modes available
Introduction

Static files are things like images, styles, and scripts that don't change often. Organizing them well helps your website load faster and stay neat.

You want to add images like logos or icons to your website.
You need to include CSS files to style your pages.
You want to add JavaScript files to make your site interactive.
You want to keep your project tidy by separating code and static files.
Syntax
Flask
project_folder/
  static/
    css/
      style.css
    js/
      script.js
    images/
      logo.png
  templates/
    index.html
  app.py

The static folder is where Flask looks for static files by default.

Inside static, you can create subfolders like css, js, and images to keep files organized.

Examples
Example of organizing CSS, JavaScript, and image files inside the static folder.
Flask
static/css/style.css
static/js/app.js
static/images/background.jpg
How to link CSS and JS files in your HTML templates using Flask's url_for function.
Flask
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<script src="{{ url_for('static', filename='js/app.js') }}"></script>
Sample Program

This simple Flask app serves an HTML page that can use static files organized in the static folder.

Put your CSS, JS, and images inside static/. In your templates/index.html, link them using url_for('static', filename='...').

Flask
from flask import Flask, render_template

app = Flask(__name__)

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

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Always use url_for('static', filename='path/to/file') to link static files. This helps Flask find them correctly.

Keep your static files organized in folders to avoid confusion as your project grows.

Remember to reload your browser or clear cache if changes to static files don't show up immediately.

Summary

Static files like CSS, JS, and images go inside the static folder.

Use subfolders inside static to keep files neat and easy to find.

Link static files in templates with url_for('static', filename='...') for correct paths.