欢迎访问宙启技术站
智能推送

在Flask中使用Flask-Bootstrap插件实现网页颜色主题切换

发布时间:2023-12-26 17:13:48

Flask-Bootstrap是一个用于在Flask应用程序中集成Bootstrap框架的插件。它允许开发人员通过简单的方法将Bootstrap的功能和样式应用到他们的网页中。

要实现网页颜色主题切换,我们可以使用Flask-Bootstrap的内置功能和一些自定义的代码。下面是一个简单的例子来演示如何使用Flask-Bootstrap实现网页颜色主题切换。

首先,需要确保已经在你的Flask应用程序中安装了Flask-Bootstrap插件。可以使用以下命令进行安装:

$ pip install flask-bootstrap

接下来,在你的Flask应用程序中导入和初始化Flask-Bootstrap插件。在app.py文件中添加以下代码:

from flask import Flask, render_template
from flask_bootstrap import Bootstrap

app = Flask(__name__)
bootstrap = Bootstrap(app)

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

if __name__ == '__main__':
    app.run()

在上面的代码中,我们导入了Flask和Bootstrap对象,并在应用程序中实例化了Bootstrap对象。然后,在index路由函数中,我们使用render_template函数来渲染一个名为index.html的模板。

接下来,我们需要创建一个名为index.html的模板文件。在templates文件夹下创建一个index.html文件,并添加以下代码:

{% extends 'bootstrap/base.html' %}

{% block title %}Color Theme Switcher{% endblock %}

{% block content %}
<div class="container">
    <h1>Color Theme Switcher</h1>
    <p>Click on the buttons below to change the color theme.</p>
    
    <button id="blue-btn" class="btn btn-primary">Blue Theme</button>
    <button id="green-btn" class="btn btn-success">Green Theme</button>
    <button id="red-btn" class="btn btn-danger">Red Theme</button>
</div>
{% endblock %}

{% block scripts %}
{{ super() }}
<script>
document.getElementById('blue-btn').addEventListener('click', function() {
    document.body.style.backgroundColor = 'blue';
});

document.getElementById('green-btn').addEventListener('click', function() {
    document.body.style.backgroundColor = 'green';
});

document.getElementById('red-btn').addEventListener('click', function() {
    document.body.style.backgroundColor = 'red';
});
</script>
{% endblock %}

在上面的代码中,我们首先继承了Flask-Bootstrap的base.html模板,然后在content块中添加了一些HTML代码。在这里,我们创建了三个按钮,分别用于切换蓝色、绿色和红色的背景颜色。在scripts块中,我们使用JavaScript代码添加了点击事件监听器,以便在点击按钮时更改背景颜色。

最后,通过运行你的Flask应用程序,可以在浏览器中访问http://localhost:5000/来查看效果。

这就是使用Flask-Bootstrap实现网页颜色主题切换的一个例子。你可以根据自己的需求进行定制和扩展。