Flask框架中的模板和自定义过滤器(十三)

一、模板和传变量的使用

  • 后端代码(传送变量到前端, **data是字典的解包过程
@app.route('/index')
def index():
    name = '小龙'
    data = {
        'city': 'huaihua',
        'sex': 'man',
        'my_list': [1, 2, 3, 4],
        'my_dict': {'hu': 'long'}
    }
    return render_template('HomePage/index_test.html', name=name, age=18, **data)
  • jinja模板
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页模板练习</title>
</head>
<body>
名字:{{ name }}<br>
年龄:{{ age }}<br>
城市:{{ city }}<br>
字典:{{ my_dict.hu }}<br>
字典:{{ my_dict['hu'] }}<br>
列表:{{ my_list[0] }}<br>
自定义字符串:{{ '你好' }}
</body>
</html>

二、过滤器的使用

1、各个过滤器如下
  • capltalize:把变量值的首字母转化成大写,其余字母转化为小写
<p>{{ 'hello' | capltalize }}</p>
  • lower:把值转化为小写
<p>{{ 'HELLO' | lower }}</p>
  • upper:把值转化为大写
<p>{{ 'hello' | upper}}</p>
  • title:把值中的每个单词的首字母都转成大写
<p>{{ 'hello world' | title}}</p>
  • trim:把值的首尾空格去掉
<p>{{ 'hello world' | trim}}</p>
  • reverse:字符串反转
<p>{{ 'olleh' | reverse}}</p>
  • safe:禁用转义
<p>{{ '<em>hello</em>' | safe}}</p>
2、例子
自定义字符串:{{ ' aab ' | reverse | title | trim}}
3、转义的用法(默认转义,用safe是禁用转义)

当在输入文本中的内容为<script>alert('你好')</script>,会在前端以原来的样式显示,如果加上{{ text : safe}}就会执行弹框。这就叫做脚本注入


@app.route('/xl', methods=['GET', 'POST'])
def xss():
    text = ''
    if request.method =='POST':
        text = request.form.get('text')
    return render_template('HomePage/xss.html', text=text)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>表单界面</title>
</head>
<body>
<form method="post">
    <textarea name="text"></textarea>
    <input type="submit" value="提交">
</form>
{{ text }}
</body>
</html>

三、自定义过滤器(两种方式)

自定义过滤器的名称如果和内置的过滤器重名,会覆盖内置的过滤器

1、通过add_template_filter(过滤器函数,模板中使用过滤器名字)
#自定义过滤器
def list_step_2(li):
    return li[::2]

#注册过滤器
#第一个参数是函数名,第二个是过滤器的名字,可在所有模板上使用
app.add_template_filter(list_step_2, 'list_step')
2、通过装饰器app.template_filter(模板中使用的装饰器的名字)
#自定义过滤器
@app.template_filter('list_step')
def list_step_2(li):
    return li[::2]
发布了21 篇原创文章 · 获赞 0 · 访问量 123

猜你喜欢

转载自blog.csdn.net/qq_41706810/article/details/105737937