自定义测试器
测试器
测试器总是返回一个布尔值,它可以用来测试一个变量或者表达式,使用”is”关键字来进行测试。
{% set name='ab' %}
{% if name is lower %}
<h2>"{{ name }}" are all lower case.</h2>
{% endif %}
测试器本质上也是一个函数,它的第一个参数就是待测试的变量,在模板中使用时可以省略去。如果它有第二个参
数,模板中就必须传进去。测试器函数返回的必须是一个布尔值,这样才可以用来给if语句作判断。
1、Jinja2中内置的测试器
官网:https://jinja.palletsprojects.com/en/master/templates/#builtin-tests
{# 检查变量是否被定义,也可以用undefined检查是否未被定义 #}
{% if name is defined %}
<p>Name is: {{ name }}</p>
{% endif %}
{# 检查是否所有字符都是大写 #}
{% if name is upper %}
<h2>"{{ name }}" are all upper case.</h2>
{% endif %}
{# 检查变量是否为空 #}
{% if name is none %}
<h2>Variable is none.</h2>
{% endif %}
{# 检查变量是否为字符串,也可以用number检查是否为数值 #}
{% if name is string %}
<h2>{{ name }} is a string.</h2>
{% endif %}
{# 检查数值是否是偶数,也可以用odd检查是否为奇数 #}
{% if 2 is even %}
<h2>Variable is an even number.</h2>
{% endif %}
{# 检查变量是否可被迭代循环,也可以用sequence检查是否是序列 #}
{% if [1,2,3] is iterable %}
<h2>Variable is iterable.</h2>
{% endif %}
{# 检查变量是否是字典 #}
{% if {'name':'test'} is mapping %}
<h2>Variable is dict.</h2>
2、自定义测试器

from flask import Flask,render_template
import re
app = Flask(__name__)
'''自定义测试器,首先创建函数,其次添加测试器'''
def test_phone(phone):
phone_re = r'1[3-9]\d{9}'
return re.match(phone_re, phone)
app.jinja_env.tests['is_phone'] = test_phone
@app.template_test('start_with')
def start_with(my_str,suffix):
return my_str.lower().startswith(suffix.lower())
模板中:
{% set tel = '18910171111' %}
{% if tel is is_phone %}
<h2>{{ tel }} is mobile phone</h2>
{% endif %}
{% set name = 'Hello world' %}
{% if name is start_with 'hello' %}
<h2>"{{ name }}" start_with "hello"</h2>
{% endif %}

浙公网安备 33010602011771号