jinja2模板过滤器介绍
- 过滤器是通过管道符号(|)进行使用的,例如:
{ { name|length }}
,将返回name的长度。 - 过滤器相当于是一个函数,把当前的变量传入到过滤器中,然后过滤器根据自己的功能,再返回相应的值,之后再将结果渲染到页面中。
jinja2过滤器
过滤器 | 说明 |
---|---|
abs | 返回一个数的绝对值 |
default | 设置默认值 |
escape或e | 转义字符,将<、>等符号转义成HTML中可展示的符号 |
first | 返回一个序列的第一个元素 |
format | 格式化字符串 |
last | 返回一个序列的最后一个元素 |
length | 返回一个序列或者字典的长度 |
join | 拼接字符串 |
safe | 如果开启全局转义,则safe过滤器将变量关掉转义 |
int | 将变量类型转为int类型 |
float | 将变量类型转为float类型 |
lower | 将字符串转换为小写 |
upper | 将字符串转换为大写 |
replace | 替换字符串 |
truncate | 截取一定长度的字符串,长度自己设置 |
striptags | 删除字符串中所有的HTML标签,如果出现多个空格,将替换成一个空格 |
trim | 截取字符串前面和后面的空白字符 |
string | 将变量转换成字符串 |
wordcount(s) | 计算一个长字符串中单词的个数 |
过滤器使用
py文件
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def test1():
content = {
'name': 'cmy',
'age': -18,
'url': '<a href="#">空链接</a>',
'cont': 'abcdefghijkl',
'list1': [1, 2, 3, 4, 5],
'str1': " haha haha haha"
}
return render_template('func.html', **content)
if __name__ == '__main__':
app.run(debug=True)
html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>abs过滤器 -> {
{ age | abs }}</p>
<p>default过滤器 -> {
{ x | default('默认') }}</p>
<p>escape过滤器 -> {
{ url | escape }}</p>
<p>list1 -> {
{ list1 }}</p>
<p>first过滤器 -> {
{ list1 | first }} </p>
<p>last过滤器 -> {
{ list1 | last }}</p>
<p>format过滤器 -> {
{ "'%s'-'%s'" | format(name, name) }}</p>
<p>length过滤器 -> name -> {
{name}} 长度-> {
{ name | length }}</p>
<p>join过滤器 -> name -> {
{name}} 拼接字符串 -> {
{ name | join("aa") }}</p>
<p>safe过滤器 -> {
{ url | safe }}</p>
<p>int过滤器 -> 1.2 -> {
{ 1.2 | int }}</p>
<p>float过滤器 -> 1 -> {
{ 1 | float }}</p>
<p>lower过滤器 -> CMY -> {
{ 'CMY' | lower }}</p>
<p>upper过滤器 -> {
{ name }} -> {
{ name | upper }}</p>
<p>replace过滤器 -> {
{ name }} -> {
{ name | replace(name, 'cmy hello') }}</p>
<p>truncate过滤器 -> {
{ cont }} -> {
{ cont | truncate(6) }}</p>
<p>striptags过滤器 -> {
{ "<p>哈哈</p>" }} -> {
{ "<p>哈哈</p>" | striptags }}</p>
<p>wordcount过滤器 -> {
{ str1 }} -> {
{ str1 | wordcount }}</p>
</body>
</html>
结果