How to use a theme file in Flask

Published on Aug. 22, 2023, 12:15 p.m.

To use a theme file in Flask, you can use the Flask-Bootstrap extension. Here are the steps to do it:

  1. Install Flask-Bootstrap with pip:
pip install Flask-Bootstrap
  1. Import and initialize the extension in your Flask application:

from flask import Flask
from flask_bootstrap import Bootstrap

app = Flask(name)
bootstrap = Bootstrap(app)


3. In your HTML templates, extend the `bootstrap/base.html` template and include the necessary blocks:

{% extends ‘bootstrap/base.html’ %}

{% block title %}My App{% endblock %}

{% block styles %}
{{ super() }}
<!– your custom CSS files here –>

{% block content %}
<!– your content here –>

{% block scripts %}
{{ super() }}
<!– your custom JavaScript files here –>


4. Optionally, you can customize the theme by overriding any of the variables defined in `bootstrap/base.html`. For example, to change the default Bootstrap color scheme, you can define a new value for the `$primary` variable before extending the base template:

{% set _primary = ‘#ff0000’ %}



By using Flask-Bootstrap, you can easily incorporate the Bootstrap framework into your Flask application and create attractive, responsive web pages.

Tags: