6.模板引擎
6.1 基本语法
- {% … %} 语句(Statements)
- {{ … }} 打印模板输出的表达式(Expressions)
- {# … #} 注释
- # … ## 行语句(Line Statements)
6.2 变量
变量类型和获取方法,可以传整型、字符串、列表、字典、函数
# 模板引擎
from flask import Flask, render_template, Markup
app = Flask(__name__)
@app.template_global()
def global_func(a, b):
"每个模板都可以调用的函数"
return a + b
def gen_input(value):
return Markup("<input value='%s'/>"%value)
@app.route('/index')
def index():
context = {
'k1':123,
'k2':[11,22,33],
'k3':{'name':'oldboy', 'age':18},
'k4':lambda x:x+1,
'k5':gen_input # 只有当前模板才能调用的函数
}
return render_template('index.html', **context)
@app.route('/order')
def order():
context = {
'k1':123,
'k2':[11,22,33]
}
return render_template('order.html', **context)
if __name__ == '__main__':
app.run()
html如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>{{ k1 }}</h1>
<h1>{{ k2.0 }} {{ k2[1] }}</h1>
<h1>{{ k3.name }} {{ k3['name'] }} {{ k3.get('name','aaa') }}</h1>
<h1>{{ k4(6) }}</h1>
<h1>{{ k5(666) }}</h1>
<h1>{{ global_func(1,2) }}</h1>
</body>
</html>
6.3 过滤器
过滤器用来修改变量,使用一个竖线和变量相隔。
{{ items|join(', ') }}
常用的内置过滤器:
- safe 渲染时不转义
- capitalize 首字母大写
- lower 小写
- upper 大写
- title 每个单词的首字母都转换成大写
- trim 去掉首尾空格
- striptags 去掉值里的HTML标签
- default 设置一个默认值,如果变量未定义,就用这个默认值替换。类似这样:
{{ my_variable|default('my_variable is not defined') }}
- random(seq) 返回一个序列里的随机元素
- truncate(s, length=255, killwords=False, end=‘…’) 截取出指定长度的文章(文章摘要)
- format(value, *args, **kwargs) 参考Python的字符串格式化函数
- length 左边如果是列表,输出列表的数量;如果是字符串,则输出字符串的长度
6.4 标签(控制语句)
语法格式 :{% 标签名 %}
if
{% if data.bool %}
<li>{{ data.bool }}值为真</li>
{% elif True %}
<li>{{ True }} 值为真</li>
{% else %}
<li>{{ data.bool }}值为假</li>
{% endif %}
for循环
{% for i in data.xxxx %}
{# 错误的迭代方法TypeError: 'bool' object is not iterable #}
{# {% for i in data.bool %}#}
<li>{{ i }}</li>
{% else %}
<li>当迭代的变量不存在时 则执行else</li>
{% endfor %}
6.5 继承
语法:
{% extends %} 继承某个模板
{% block %} 挖坑和填坑
{{ super() }} 调用被替换掉的代码
如下:
base.html:被继承的模板
<!DOCTYPE html>
<html lang="en">
<head>
{% block header %}
<meta charset="UTF-8">
{% block meta %}
{% endblock %}
<title>{% block title%}首页{% endblock %}</title>
<style>
{% block style %}
p{color:red;}
{% endblock %}
</style>
{% block link %}
{% endblock %}
{% block script %}
{% endblock %}
{% endblock %}
</head>
<body>
<header>头部</header>
{% block con %}
我是中间的内容部分
{% endblock %}
<footer>尾部</footer>
</body>
</html>
extend.html:继承base.html的模板
{% extends 'base.html' %}
{% block title %}
我的首页
{% endblock %}
{% block style %}
{{ super() }}
p{color:green;}
{% endblock %}
{% block con %}
<p>{{ super() }}</p>
{% endblock %}
参考:
https://zhuanlan.zhihu.com/p/23669244
https://www.jianshu.com/p/e20e3671c680