Flask Web 开发 Chapter3 - 模板

Jinja2模板引擎

最简单的模版:

index.html
<h1>Hello world,{{name}}</h1>

渲染模板:

from flask import Flask,render\_template
@app.route('/user/<name>')
  render_template('index.html’,name)

变量与控制结构

  1. Jinja2提供变量,用{{ name }}包裹变量
  2. 变量支持复杂类型 列表、字典、对象 甚至是函数
  3. Jinja2变量还支持过滤器 name | capitalize
  4. 提供if、for循环控制结构
{% if name == 'admin' %}
admin is coming...
{% else %}
user is coming...
{% endif %}
  1. 支持宏 {% macro render(comment) %}
  2. 支持继承,可以方便的控制模板继承

Flask-Bootstrap

Bootstrap 是Twitter开发的开源框架,提供用户界面组件,创建网页
在Flask 中,install Flask-Bootstrap可以快速集成Bootstrap
只需要提供Bootstrap模板,可以快速制作出网页

from flask.ext.bootstrap import Bootstrap
bootstrap = Bootstrap(app)

自定义错误页面

404和500错误码可以使用基于模板的页面

@app.errorhandler(404)
def page\_not\_found(e):
 return render\_template(‘404.html’),404

静态文件

静态文件的引用被当成一个特殊的路由 /static/<filename>
默认设置在static文件目录中存放文件

本地化日期和时间

服务器一般用协调世界时间(UTC),一般是时间发送给web浏览器,转换成当地时间
使用Flask-Moment可以快速实现

moment = Moment(app)
render\_template(‘index.html’,current\_time=datetime.utcnow())

index.html:

# L到LLLL对应不同的复杂度
{{moment(current\_time).format(‘LLL’)}}
# 随着时间推移自动刷新时间
{{moment(current\_time).fromNow(refresh=True)}}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容