二、摸版
摸版
render_template 渲染摸版,会在程序文件夹中 templates 子文件夹中寻找模板
Jinja2摸版
mkdir templates
echo '<h1>Hello, World!</h1>' > templates/index.html
echo '<h1>Hello, {{ name }}!</h1>' > templates/user.html
(myproject) [root@localhost myproject]# python app.pyfrom flask import Flask, render_template
app = Flask(__name__)
app.debug = True
@app.route('/')
def index():
return render_template('index.html')
@app.route('/user/<name>')
def user(name):
return render_template('user.html', name=name)
if __name__ == '__main__':
app.run(host='0.0.0.0',port=8080)测试
变量过滤器
Jinja2 能识别所有类型的变量,甚至是一些复杂的类型,例如列表、字典和对象。在模板 中使用变量的一些示例如下:
safe
渲染值时不转义
capitalize
把值的首字母转换成大写,其他字母转换成小写
lower
把值转换成小写形式
upper
把值转换成大写形式
title
把值中每个单词的首字母都转换成大写
trim
把值的首尾空格去掉
striptags
渲染之前把值中所有的 HTML 标签都删掉
IF控制器
For控制器
宏控制器
为了重复使用宏,我们可以将其保存在单独的文件中,然后在需要使用的模板中导入:
需要在多处重复使用的模板代码片段可以写入单独的文件,再包含在所有模板中,以避免重复:
摸版继承
创建基础摸版,可被其他摸版调用: base.html
基模板的衍生模板
注意新定义的 head 块,在基模板中其内容不是空的,所以使用 super() 获取原来的内容
集成 Bootstrap
使用 Flask-Bootstrap 的模板
Bootstrap-Flask的出现是为了替代不够灵活且缺乏维护的Flask-Bootstrap。它的主要设计参考了Flask-Bootstrap,其中渲染表单和分页部件的宏基于Flask-Bootstrap中的相关代码修改实现。和Flask-Bootstrap相比 参考: https://zhuanlan.zhihu.com/p/39799223 参考:https://bootstrap-flask.readthedocs.io/en/stable/basic.html#configurations https://bootstrap-flask.readthedocs.io/en/stable/advanced.html#bootswatch-theme
base.html 不变
templates/user.html:使用 Flask-Bootstrap 的模板

Flask-Bootstrap 的 base.html 模板还定义了很多其他块,都可在衍生模板中使用。
Flask-Bootstrap基模板中定义的块
doc
整个 HTML 文档
html_attribs
标签的属性
html
标签中的内容
head
标签中的内容
title
标签中的内容
metas 一组
标签
styles
层叠样式表定义
body_attribs
标签的属性
body
标签中的内容
navbar
用户定义的导航条
content
用户定义的页面内容
scripts
文档底部的 JavaScript 声明
自定义错误页面
templates/404.html:使用模板继承机制自定义 404 错误页面
链接
Flask 提供了 url_for() 辅助函数,它可以使用程序 URL 映射中保存的信息生成 URL。
url_for() 函数最简单的用法是以视图函数名(或者 app.add_url_route() 定义路由时使用的端点名)作为参数,返回对应的 URL
静态文件
示例
使用Flask-Moment本地化日期和时间
一个优雅的解决方案是,把时间单位发送给 Web 浏览器,转换成当地时间,然后渲染。Web 浏览器可以更好地完成这一任务,因为它能获取用户电脑中的时区和区域设置。 Flask-Moment 是一个 Flask 程序扩展,能把moment.js 集成到 Jinja2 模板中。
templates/base.html:引入 moment.js 库
如何使用
Last updated