当前位置:Gxlcms > Python > python中Jinja2是什么?如何使用?

python中Jinja2是什么?如何使用?

时间:2021-07-01 10:21:17 帮助过:713人阅读

本篇文章给大家带来的内容是关于python中Jinja2是什么?如何使用?,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

什么是Jinja2

Jinja2是Python下一个被广泛应用的模版引擎,他的设计思想来源于Django的模板引擎,并扩展了其语法和一系列强大的功能。其中最显著的一个是增加了沙箱执行功能和可选的自动转义功能,这对大多应用的安全性来说是非常重要的。

基于unicode并能在python2.4之后的版本运行,包括python3。

如何使用Jinja2

要想使用Jinja2模板,需要从flask导入render_template函数,然后在路由函数中调用render_template函数,该函数第一个参数就是模板名字。模板默认保存在目录。

最简单的模板文件就是普通的HTML文件,但静态文件没什么意义,需要在访问路由时传入响应的参数,并在模板中以一定的样式显示在浏览器中,因此,需要用到render_template函数的关键字参数。假设有一个模板文件hello.html,代码如下:

  1. <h1> hello,{{name}}.</h1>

这个用{{......}}括起来的部分就是模板表达式。在使用render_template函数调用模板文件hello.html时,需要通过关键字参数指定name值。

  1. render_template('hello.html',name='star')

返回给客户端时,{{name}}会被替换成star.
网页输出代码

  1. <h1> hello,star.</h1>

jinja2常用语法

  1. 1.变量显示语法: {{ 变量名 }}
  2. 2. for循环:
  3. {% for i in li%}
  4. {% endfor %}
  5. 3. if语句
  6. {% if user == 'westos'%}
  7. {% elif user == 'hello' %}
  8. {% else %}
  9. {% endif%}

数据显示

  1. # templates目录里面建立mubna.html文件
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5. <meta charset="UTF-8">
  6. <title>hello</title>
  7. </head>
  8. <body>
  9. <p>变量:{{ name }}</p>
  10. <p>列表:{{ li }}</p>
  11. <p>列表元素:
  12. {% for item in li %}
  13. <br/>{{ item }}
  14. {% endfor %}</p>
  15. <p>字典:{{ d }}</p>
  16. <p>字典元素:
  17. {{ d.a }}
  18. {{ d['b'] }}</p>
  19. <p>对象:{{ u }}</p>
  20. <table>
  21. <tr>
  22. <td>用户</td>
  23. <td>密码</td>
  24. </tr>
  25. <tr>
  26. <td>{{ u.name }}</td>
  27. <td>{{ u.passwd }}</td>
  28. </tr>
  29. </table>
  30. </body>
  31. </html>
  1. from flask import Flask, render_template
  2. app = Flask(__name__)
  3. class User(object):
  4. def __init__(self, name, passwd):
  5. self.name = name
  6. self.passwd = passwd
  7. def __str__(self):
  8. return "<User: %s>" %(self.name)
  9. @app.route('/')
  10. def index1():
  11. name = "sheen is cute !!"
  12. li = [1, 2, 4, 5]
  13. d = dict(a=1, b=2)
  14. u = User("westos", "passwd")
  15. return render_template('muban.html',
  16. name = name,
  17. li = li,
  18. d = d,
  19. u = u
  20. )
  21. app.run()

2949133028-5bd13033e2dcc_articlex.png

模板中的过滤器

服务端给客户端返回的数据可能来自于多种数据源。这些数据格式可能并不能满足客户端需求,就需要对数据进行再加工。
过滤器需要放在模板表达式变量的后面,与变量之间用'|'分割,{{ vlaue|upper}}将value英文字母都转换为大写形式。

编写一个时间过滤器,将时间戳转换为特定格式的字符串时间

  1. from flask import Flask, render_template
  2. import time
  3. app = Flask(__name__)
  4. def time_format(value,format="%Y-%m-%d %H:%M:%S"):
  5. # 时间戳----> 元组
  6. t_time = time.localtime(value)
  7. # 元组 ----> 指定字符串
  8. return time.strftime(format,t_time)
  9. # 第一个参数是过滤器函数,第二个参数是过滤器名称
  10. app.add_template_filter(time_format,'time_format')
  11. @app.route('/chtime/')
  12. def chtime():
  13. return render_template('chtime.html',timestamp = time.time())
  14. app.run()
  1. # templates/目录下的chtime.html
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5. <meta charset="UTF-8">
  6. <title>Title</title>
  7. </head>
  8. <body>
  9. 时间戳
  10. {{ timestamp }}
  11. <br/>
  12. 格式化后的时间
  13. {{ timestamp | time_format }}
  14. </body>
  15. </html>

2715859521-5bd13071c2ff8_articlex.png

宏操作

在编写python程序时,会有很多地方调用同样或类似的代码。这种情况,可以把重复使用的代码放到函数或类中,只需要访问函数或类的实例就可以实现代码复用。Jinja2 模板中使用宏来防止代码冗余。

Jinja2 模板中的宏需要放到{%......%},使用修饰,支持参数,并且使用{% endmacro %}结束

如果宏要被多个模板文件共享,就需要将宏单独放到一个模板文件中,然后使用{% import ….%}指令导入该模板

调用宏,实现登陆页面的模板继承

  1. ## templates/目录下的macro.html
  2. {% macro input(type, name, text ) %}
  3. <p class="form-group">
  4. <label>{{ text }}</label>
  5. <input name={{ name }} type={{ type }} class="form-control">
  6. </p>
  7. {% endmacro %}
  1. # # templates/目录下的login.html
  2. {% extends "base.html" %}
  3. {% block title %}
  4. 登陆
  5. {% endblock %}
  6. {% block content %}
  7. <p class="container container-small">
  8. <h1>登录
  9. <small>没有账号?<a href="signup.html">注册</a></small>
  10. </h1>
  11. {# /*将表单信息提交给/login路由对应的函数进行处理, 并且提交信息的方式为post方法, 为了密码的安全性*/#}
  12. <form action="/login/" method="post">
  13. <!--<p class="form-group">-->
  14. <!--<label>用户名/手机/邮箱</label>-->
  15. <!--<input name="user" type="text" class="form-control">-->
  16. <!--</p>-->
  17. {% import 'macro.html' as macro %}
  18. {#调用宏模板#}
  19. {{macro.input('text', 'user', "用户名/手机/邮箱" )}}
  20. {{macro.input('password','passwd', "密码" )}}
  21. <!--<p class="form-group">-->
  22. <!--<label>密码</label>-->
  23. <!--<input name="passwd" type="password" class="form-control">-->
  24. <!--</p>-->
  25. <p class="form-group">
  26. <button class="btn btn-primary btn-block" type="submit">登录</button>
  27. </p>
  28. <p class="form-group">
  29. <a href="#">忘记密码?</a>
  30. </p>
  31. <!--获取服务器传递给后台的变量message, jinja2模板引擎里面的语法-->
  32. {% if message %}
  33. <p style="color: red">{{ message }}</p>
  34. {% endif %}
  35. </form>
  36. </p>
  37. {% endblock %}
  1. #主程序
  2. from flask import Flask, render_template
  3. app = Flask(__name__)
  4. @app.route('/login/')
  5. def login():
  6. return render_template('login.html')
  7. app.run()

2982924092-5bd130d6f192b_articlex.png

模板继承

Jinja2模板还有另一种代码复用技术,就是模板继承。当一个模板被另外的模板继承时,可以通过{{ super() }} 访问父模板的资源。在一个模板中继承另一个模板,需要extends 指令。如 child.txt 模板文件从 parent.txt 继承的代码

  1. {% extends ‘parents.txt’ %}

child.txt 从parent.txt模板继承后,会自动使用parent.txt 中的所有代码,但要放在

  1. {% block xxxx%} .... {% endblock %}

中的代码需要child.txt中使用{{super() }}引用。其中,xxxx是块(block)的名字
模板继承语法:

  1. 1. 如何继承某个模板?
  2. {% extends "模板名称" %}
  3. 2. 如何挖坑和填坑?
  4. 挖坑:
  5. {% block 名称 %}
  6. 默认值
  7. {% endblock %}
  8. 填坑:
  9. {% block 名称 %}
  10. {% endblock %}
  11. 3. 如何调用/继承被替代的模板?
  12. 挖坑:
  13. {% block 名称 %}
  14. 默认值
  15. {% endblock %}
  16. 填坑:
  17. {% block 名称 %}
  18. #如何继承挖坑时的默认值?
  19. {{ super() }}
  20. # 后面写新加的方法.
  21. ........
  22. {% endblock %}
  1. #templates目录下建立parent.html模板文件
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5. {% block head %}
  6. <meta charset="UTF-8">
  7. <title>{% block title %}hello{% endblock %}</title>
  8. {% endblock %}
  9. </head>
  10. <body>
  11. I LOVE PYTHON! <br/>
  12. {% block body %}
  13. Cute,{{ text }}
  14. {% endblock %}
  15. </body>
  16. </html>
  1. #templates目录下建立child.html模板文件
  2. {% extends 'parent.html' %}
  3. {% block title %}
  4. {#继承挖坑时的默认值:{{ super() }}#}
  5. {{ super() }}-{{ text }}
  6. {% endblock %}
  7. {% block body %}
  8. <h1>{{ super() }},Beauty!</h1>
  9. {% endblock %}
  1. # 主程序
  2. from flask import Flask,render_template
  3. app = Flask(__name__)
  4. @app.route('/')
  5. def index():
  6. return render_template('child.html',text = 'sheen')
  7. if __name__ == '__main__':
  8. app.run()

1311899705-5bd1310a8c152_articlex.png

以上就是python中Jinja2是什么?如何使用?的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行