This article brings you what is Jinja2 in python? how to use? , has certain reference value, friends in need can refer to it, I hope it will be helpful to you.
What is Jinja2
Jinja2 is the next widely used template engine in Python. Its design ideas are derived from Django’s template engine and expanded Its syntax and set of powerful features. The most significant one is the addition of sandbox execution capabilities and optional automatic escaping capabilities, which are very important for the security of most applications.
Based on unicode and can run on versions after python2.4, including python3.
How to use Jinja2
To use Jinja2 template, you need to import the render_template function from flask, and then call the render_template function in the routing function. The first parameter of this function is Template name. Templates are saved in the directory by default.
The simplest template file is an ordinary HTML file, but static files are meaningless. You need to pass in the response parameters when accessing the route, and display them in the browser in a certain style in the template. Therefore, You need to use the keyword parameters of the render_template function. Suppose there is a template file hello.html, the code is as follows:
<h1> hello,{{name}}.</h1>
The part enclosed by {{...}} is the template expression. When using the render_template function to call the template file hello.html, you need to specify the name value through keyword parameters.
render_template('hello.html',name='star')
When returned to the client, {{name}} will be replaced by star.
Web page output code
<h1> hello,star.</h1>
jinja2 common syntax
1.变量显示语法: {{ 变量名 }} 2. for循环: {% for i in li%} {% endfor %} 3. if语句 {% if user == 'westos'%} {% elif user == 'hello' %} {% else %} {% endif%}
Data display
# templates目录里面建立mubna.html文件 nbsp;html> <meta> <title>hello</title> <p>变量:{{ name }}</p> <p>列表:{{ li }}</p> <p>列表元素: {% for item in li %} <br>{{ item }} {% endfor %}</p> <p>字典:{{ d }}</p> <p>字典元素: {{ d.a }} {{ d['b'] }}</p> <p>对象:{{ u }}</p>
用户 | 密码 |
{{ u.name }} | {{ u.passwd }} |
from flask import Flask, render_template app = Flask(__name__) class User(object): def __init__(self, name, passwd): self.name = name self.passwd = passwd def __str__(self): return "<user:>" %(self.name) @app.route('/') def index1(): name = "sheen is cute !!" li = [1, 2, 4, 5] d = dict(a=1, b=2) u = User("westos", "passwd") return render_template('muban.html', name = name, li = li, d = d, u = u ) app.run()</user:>
Filter in template
The data returned by the server to the client may come from a variety of data sources. These data formats may not meet the client's needs, and the data needs to be reprocessed.
The filter needs to be placed after the template expression variable and separated from the variable by '|'. {{ vlaue|upper}} converts all English letters of value into uppercase.
Write a time filter to convert the timestamp into a string time in a specific format
from flask import Flask, render_template import time app = Flask(__name__) def time_format(value,format="%Y-%m-%d %H:%M:%S"): # 时间戳----> 元组 t_time = time.localtime(value) # 元组 ----> 指定字符串 return time.strftime(format,t_time) # 第一个参数是过滤器函数,第二个参数是过滤器名称 app.add_template_filter(time_format,'time_format') @app.route('/chtime/') def chtime(): return render_template('chtime.html',timestamp = time.time()) app.run()
# templates/目录下的chtime.html nbsp;html> <meta> <title>Title</title> 时间戳 {{ timestamp }} <br> 格式化后的时间 {{ timestamp | time_format }}
Macro operation
When writing a python program, there will be many places where the same or similar code is called. In this case, you can put the reused code into a function or class, and you only need to access the instance of the function or class to achieve code reuse. Macros are used in Jinja2 templates to prevent code redundancy.
The macros in the Jinja2 template need to be placed in {%......%}, use modifications, support parameters, and end with {% endmacro %}
If the macro is to be used multiple times To share a template file, you need to put the macro into a template file separately, and then use the {% import ....%} command to import the template
Call the macro to realize the template inheritance of the login page
## templates/目录下的macro.html {% macro input(type, name, text ) %} <p> <label>{{ text }}</label> <input> </p> {% endmacro %}
# # templates/目录下的login.html {% extends "base.html" %} {% block title %} 登陆 {% endblock %} {% block content %} <p> </p><h1>登录 <small>没有账号?<a>注册</a></small> </h1> {# /*将表单信息提交给/login路由对应的函数进行处理, 并且提交信息的方式为post方法, 为了密码的安全性*/#}
#主程序 from flask import Flask, render_template app = Flask(__name__) @app.route('/login/') def login(): return render_template('login.html') app.run()
Template inheritance
Jinja2 template has another code reuse technology, which is Template inheritance. When a template is inherited by another template, the resources of the parent template can be accessed through {{ super() }}. Inheriting a template from another template requires the extends directive. For example, the child.txt template file inherits the code from parent.txt
{% extends ‘parents.txt’ %}
After child.txt inherits from the parent.txt template, all the code in parent.txt will be automatically used, but it must be placed in
{% block xxxx%} .... {% endblock %}
needs to be referenced using {{super() }} in child.txt. Among them, xxxx is the name of the block
Template inheritance syntax:
1. 如何继承某个模板? {% extends "模板名称" %} 2. 如何挖坑和填坑? 挖坑: {% block 名称 %} 默认值 {% endblock %} 填坑: {% block 名称 %} {% endblock %} 3. 如何调用/继承被替代的模板? 挖坑: {% block 名称 %} 默认值 {% endblock %} 填坑: {% block 名称 %} #如何继承挖坑时的默认值? {{ super() }} # 后面写新加的方法. ........ {% endblock %}
#templates目录下建立parent.html模板文件 nbsp;html> {% block head %} <meta> <title>{% block title %}hello{% endblock %}</title> {% endblock %} I LOVE PYTHON! <br> {% block body %} Cute,{{ text }} {% endblock %}
#templates目录下建立child.html模板文件 {% extends 'parent.html' %} {% block title %} {#继承挖坑时的默认值:{{ super() }}#} {{ super() }}-{{ text }} {% endblock %} {% block body %} <h1>{{ super() }},Beauty!</h1> {% endblock %}
# 主程序 from flask import Flask,render_template app = Flask(__name__) @app.route('/') def index(): return render_template('child.html',text = 'sheen') if __name__ == '__main__': app.run()
The above is the detailed content of What is Jinja2 in python? how to use?. For more information, please follow other related articles on the PHP Chinese website!