Bootstrap-Flask
Bootstrap-Flask is a collection of Jinja macros for Bootstrap 4 & 5 and Flask. It helps to render Flask-related data and objects to Bootstrap markup HTML more easily, such as Flask-WTF forms, data tables, and pagination. The library is actively maintained, with a recent release of 2.5.0, and typically sees updates to align with new Bootstrap versions and address Python compatibility.
Warnings
- breaking Migration from the older `Flask-Bootstrap` library to `Bootstrap-Flask` requires full uninstallation of `Flask-Bootstrap` before installing `bootstrap-flask`. They cannot coexist in the same environment and use different template paths.
- breaking Since version 2.0.0, the generic `Bootstrap` class and the `bootstrap/` template path are deprecated. Users must now explicitly choose and initialize `Bootstrap4` for Bootstrap 4 or `Bootstrap5` for Bootstrap 5.
- deprecated Python 3.6 support was dropped in version 2.2.0.
- deprecated Python 3.7 and 3.8 support was dropped in version 2.5.0.
Install
-
pip install bootstrap-flask
Imports
- Bootstrap5
from flask_bootstrap import Bootstrap5
- Bootstrap4
from flask_bootstrap import Bootstrap4
- Bootstrap
N/A
Quickstart
from flask import Flask, render_template
from flask_bootstrap import Bootstrap5
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired, Length
import os
app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'a_default_secret_key_for_dev')
bootstrap = Bootstrap5(app)
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired(), Length(1, 20)])
password = PasswordField('Password', validators=[DataRequired(), Length(8, 150)])
remember = BooleanField('Remember me')
submit = SubmitField('Log In')
@app.route('/', methods=['GET', 'POST'])
def index():
form = LoginForm()
if form.validate_on_submit():
# In a real application, process the form data (e.g., login user)
return f"Login successful for {form.username.data}! Remember me: {form.remember.data}"
return render_template('index.html', form=form)
# To run this, save it as app.py and create a 'templates' folder.
# Inside 'templates', create 'index.html' with the following content:
#
# <!doctype html>
# <html lang="en">
# <head>
# <meta charset="utf-8">
# <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
# <title>Login</title>
# {{ bootstrap.load_css() }}
# </head>
# <body>
# <div class="container">
# <h2 class="mt-3">Login</h2>
# {% from 'bootstrap5/form.html' import render_form %}
# {{ render_form(form) }}
# </div>
# {{ bootstrap.load_js() }}
# </body>
# </html>
#
# Then install dependencies:
# pip install flask bootstrap-flask flask-wtf
# And run:
# export SECRET_KEY='your_strong_secret_key' # or set on Windows/Powershell
# flask run