Flask 入门(2):添加导航条

给网站添加导航条。

Bootstrap 官网有很多现成的例子:Examples · Bootstrap,在这个例子中,我的目的要到达在网站中加入一个导航条,并修改导航条的链接文字。

首先,新建空白页面,这再简单不过了,运行代码,这个页面非常简单,首页只有一行“Hello, World”

1
2
3
4
5
6
7
8
9
10
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def hello_world():
return 'Hello, World!'

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

在搭建网站中,现有的框架已经很成熟,我们不需要为了实现一个功能而从头开始造轮子,直接调用即可,节省了大量的开发时间。比如,Bootstrap 是一个强大的前端框架,里面有很多组件即拿即用。

Bootstrap

然而,仅仅返回“Hello, World!”字符串远远不能满足需求,网页中实现各种特效还得依靠 HTML 和 CSS 这些标记语言,Flask 的 render_template() 方法,字面上即“提交模板”,我们在模板中设计好样式后,Flask 再将完整的 HTML 文件提交给浏览器展示。

templates 文件夹下新建 index.html 作为主页,

1
2
3
4
5
6
7
8
{% extends 'layout.html' %}

{% block body %}
<div class="jumbotron text-center">
<h1>这是一个 Flask 示例网站!</h1>
<p class="lead">Flask 是一个快速的网络框架!</p>
</div>
{% endblock %}

layout.html 作为主页的样式模板,还要在 templates 文件夹下新建 includes文件夹,把导航条的代码(按住 F12 查看网页源代码)复制到includes/_navibar.html文件中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html lang="en">
<link>
<meta charset="UTF-8">
<title>My Flask APP</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"></link>
</head>
<body>
{% include 'includes/_navibar.html' %}
<div class="container">
{% block body %}{% endblock %}
</div>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"></script>
</body>
</html>

最后,还需要修改 app 的代码:

1
2
3
4
5
6
7
8
9
10
from flask import Flask, render_template

app = Flask(__name__)

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

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

整个执行的过程是,Flask 先访问 index.html 文件,然后该文件的样式由 layout.html 决定,layout.html中再引入导航条的源代码,最后实现的效果。

导航条

------本文结束,欢迎收藏本站、分享、评论或联系作者!------
点击查看
赠人玫瑰 手有余香
0%