jinja2模版
from flask import Flask,render_template app = Flask (__name__) @app.route ('/<name>') def index(name): return render_template('index.html',name=name) @app.route ('/user/<name>') def user(name): return render_template('user.html',name=name) if __name__ == '__main__': app.run (debug=True)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> Hello! {{ name|capitalize }} </body> </html>
jinja2 能识别所有类型的变量,比如列表,字典,对象
<p>{{ mylist[3]}}</p> <p>{{ mydict['key']}}</p> <p>{{ mylist['key']}}</p> <p>{{ myobj.somemethod() }}</p>
过滤器
safe 渲染值时不转义
capitalize 把值的首字母转换成大写,其他字母小写
lower 把值转换成小写形式
upper 把值转换成大写形式
title 把值中每个单词的首字母变成大写
trim 把值的首尾空格去掉
striptags 渲染之前把所有的HTML标签都删除
控制结构
if条件控制
{% if user %}
hello {{ user }}
{% else %}
hello,stranger!
{% endif %}
for 循环
<ul> {% for comment in comments %} <li>{{ comment }}</li> {% endfor %} </ul>
宏(函数)
{% macro render_comment(comment) %} #声明一个宏(函数)
<li>{{ comment }}</li> # return 值
{% endmacro %} #结束
<ul>
{% for comment in comments %}
{{ render_comment(comment) }} #调用宏
{% endfor %}
</ul>
导入宏
{% import 'macros.html' as macros %}
<ul>
{% for comment in comments %}
{{ macros.render_comment(comment) }}
{% endfor %}
</ul>
模版继承
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> {% block head %} <title>{% block title %}{% endblock %}- my application</title> {% endblock %} </head> <body> {% block body %} {% endblock %} </body> </html>