Flask-Bootstrap 和 Flask-Nav 是两个用于美化 Flask 应用的扩展。Flask-Bootstrap 提供了 Bootstrap 的集成,而 Flask-Nav 则用于创建导航栏。Flash 消息是一种在 Flask 中传递一次性消息的方法,通常用于显示成功、警告或错误信息。
下面是如何在 Flask 应用中使用 Flask-Bootstrap 和 Flask-Nav 显示 Flash 消息的步骤:
首先,确保你已经安装了 Flask-Bootstrap 和 Flask-Nav:
pip install Flask-Bootstrap Flask-Nav
在你的 Flask 应用中配置这两个扩展:
from flask import Flask, flash
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_nav.elements import Navbar, View, Subgroup
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key' # 必须设置一个密钥
bootstrap = Bootstrap(app)
nav = Nav(app)
@nav.navigation()
def mynavbar():
return Navbar(
'My App',
View('Home', 'index'),
Subgroup('Settings',
View('Profile', 'profile'),
View('Logout', 'logout')
)
)
@app.route('/')
def index():
flash('Welcome to our site!', 'success')
return render_template('index.html')
@app.route('/profile')
def profile():
flash('This is your profile page.', 'info')
return render_template('profile.html')
@app.route('/logout')
def logout():
flash('You have been logged out.', 'warning')
return redirect(url_for('index'))
在你的模板文件中使用 Flask-Bootstrap 提供的 flash
宏来显示 Flash 消息。例如,在 base.html
中:
{% extends "bootstrap/base.html" %}
{% block content %}
{{ nav.topbar() }}
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{ category }}">
{{ message }}
</div>
{% endfor %}
{% endif %}
{% endwith %}
{% block page_content %}{% endblock %}
{% endblock %}
然后在具体的页面模板中继承 base.html
:
{% extends "base.html" %}
{% block page_content %}
<h1>Welcome to the Home Page</h1>
<!-- 其他内容 -->
{% endblock %}
现在当你访问不同的路由时,应该能看到相应的 Flash 消息。
get_flashed_messages
函数用于获取并清除已显示的 Flash 消息。success
, info
, warning
, danger
),并在 CSS 中定义相应的样式。通过这种方式,你可以优雅地在 Flask 应用中使用 Flask-Bootstrap 和 Flask-Nav 来显示和管理 Flash 消息。
领取专属 10元无门槛券
手把手带您无忧上云