当前位置: 代码迷 >> 综合 >> JinJa2-测试器
  详细解决方案

JinJa2-测试器

热度:43   发布时间:2023-11-25 02:29:58.0

测试器

测试器总是返回一个布尔值,它可以用来测试一个变量或者表达式,使用”is”关键字来进行测试

测试器本质上也是一个函数,它的第一个参数就是待测试的变量,在模板中使用时可以省略去。如果它有第二个参数,模板中就必须传进去。测试器函数返回的必须是一个布尔值,这样才可以用来给if语句作判断

1、Jinja2中内置的测试器
JinJa2官网

{# 检查变量是否被定义,也可以用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>{% endif %}

2、自定义测试器

from flask import Flask, render_template
import reapp = Flask(__name__)@app.route("/my_test")
def index():return render_template("my_test.html")def is_phone_number(number: str) -> Optional[Match[str]]:reg = "1[3,5,6,7,8,9]\d{9}"return re.match(reg, number)
# 第一种方式
app.jinja_env.tests["test_phone"] = is_phone_number
# 第二种方式
@app.template_test("start_with")
def start_with_test(test_str: str, exp: str) -> bool:return test_str.startswith(exp)if __name__ == '__main__':app.run(host="0.0.0.0", port=8088, debug=True)

模板

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>自定义测试器</title>
</head>
<body>{% if "13154087526" is test_phone %}<p>is phone number</p>{% endif %}{% if "我爱你,塞北的雪" is start_with("我") %}<p>start with me</p>{% endif %}
</body>
</html>

结果

is phone number
start with me