第三章 模板

3.1 jinja2模板引擎

<h1>Hello, {{ name }}!</h1>

3.3.1 渲染模板

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

@app.route('/user/<name>')
def user(name):
    return render_template('user.html', name=name)

3.1.2 变量

<p>一个来自字典的值: {{ mydict['key'] }}.</p>
<p>一个来自列表的值: {{ mylist[3] }}.</p>
<p>一个来自列表的值,使用变量索引: {{  mylist[myintvar] }}.</p>
<p>一个来自对象的方法的值: {{ myobj.somemethod() }}.</p>

还可以使用过滤器改变变量的值--查看完整过滤器列表

Hello, {{ name|capitalize }}

3.1.3 控制结构

page22->包括ifelse/for/页面定义函数(宏)/导入页面/继承

base模板中非空内容使用super函数获取原内容再在下方添加新内容
{{ super() }}

3.2 使用 Flask-Bootstrap 集成 Twitter Bootstrap

略感鸡肋

3.3 自定义错误页面

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404


@app.errorhandler(500)
def internal_server_error(e):
    return render_template('500.html'), 500

3.4 链接

{{ url_for('index', _external=True) }}

3.5 静态文件

{% block head %}
{{ super() }}
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
<link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
{% endblock %}

3.6 使用Flask-Moment本地化日期和时间

from flask_moment import Moment
moment = Moment(app)


@app.route('/')
def index():
    return render_template('index.html',
                           current_time=datetime.utcnow())
<p>The local date and time is {{ moment(current_time).format('LLL') }}.</p>
<p>That was {{ moment(current_time).fromNow(refresh=True) }}.</p>

更多moment函数:http://momentjs.com/docs/#/displaying/

中文本地化:在head中加入
{{ moment.lang('zh-CN') }}
原文地址:https://www.cnblogs.com/jt-huang/p/6018323.html