Flask Static Files Using Static Files


Web applications often require static files like CSS or JavaScript files. To use static files in a Flask application, create a folder called static in your package or next to your module and it will be available at /static on the application.

An example project structure for using templates is as follows:


app.py is a basic example of Flask with template rendering.

from flask import Flask, render_template

app = Flask(__name__)

def index():
    return render_template('index.html')

To use the static CSS and JavaScript file in the template index.html, we need to use the special 'static' endpoint name:

{{url_for('static', filename = 'style.css')}}

So, index.html may contain:

        <title>Static File</title>
        <link href="{{url_for('static', filename = 'style.css')}}" rel="stylesheet">
        <script src="{{url_for('static', filename = 'script.js')}}"></script>
        <h3>Hello World!</h3>

After running app.py we will see the webpage in http://localhost:5000/.