Basic usage of template engine Jinja2

Flask provides a template engine is Jinja2, easy to use and powerful.
Template is just a text file that can generate any text-based format (HTML, XML, CSV, LaTex and so on). 
It is not a specific extension, .html, or .xml are possible.
Template contains variable or expression, both of which will be replaced with values when the template evaluation. There is also a template tag, the control logic templates.
Jinja2 document: http: //docs.jinkan.org/docs/jinja2/index.html

Here are some use cases involving template continues, variable assignments, loops, go blank, escaped block, conditional statements and so on.
1, create a basic template files in the directory templates below base.html

<!doctype html>
<html>
	<head>
		<title>{{title}}</title>
		<style text="text/css">
			ul{list-style:none}
			li{padding-left:20px}
		</style>
	</head>
	<body>	
		<div id="content">
		  <h4>子模板内容</h4>
		   {% block content %}
		   
		   {% endblock %}
		</div>
	</body>
</html>

2, also create a sub-template files in the directory templates below test1.html

{% extends 'base.html' %}
{# 这里是注释,上面标签表示当前模板继承自模板base.html  #}	

{% block content %}

    变量:{{v1}}
	 <br />
	 
	 赋值:
	 {% set v2 = 100 %}
	 {{v2}}
	 <br />	 	 
	 
    循环:
	{% for item in items%}
		{{ item.name }}
	{% endfor %}
	 <br />	
	 	 
	去空白:
	{% for item in items -%}
		{{ item.name }}
	{%- endfor %}
	 <br />
	 
	 转义块:
	 {% raw %}
	    <ul>
		 {% for item in list -%}
			<li>{{ item }}</li>
		 {%- endfor %}
		</ul>
	 {% endraw %}
	 
	 条件语句:
	 {% for item in items%}
		{% if item.name == '张三' %} {{item.name}}(管理员)
		{% else %} {{item.name}}
		{% endif %} 		
	{% endfor %}
	<br />

    <form method="post" action="/getFormValue">
		 <input type="text" name="username" width="60" />
		 <input type="submit" value="获取表单值" />		  
	</form>
	
{% endblock %}

3. Create test1.py catalog templates on the same level directory

from flask import Flask, render_template, request

app = Flask(__name__) 

@app.route('/test1')
def test1() -> 'html':  
  items = [{'name':'张三'},
          {'name':'李四'},
          {'name':'王五'}]
  return render_template('test1.html',
                         title='test',
                         v1='变量值',
                         items = items)


@app.route('/getFormValue', methods=['POST'])
def getFormValue() -> 'str':
  username = request.form['username'] 
  return username

app.run(debug = True)

4, execution py -3 test1.py at the command prompt
to access http://127.0.0.1:5000/test1, the page appears as follows:

子模板内容
变量:变量值 
赋值: 100 
循环: 张三 李四 王五 
去空白: 张三李四王五 
转义块:
{% for item in list -%}
{{ item }}
{%- endfor %}
条件语句: 张三(管理员) 李四 王五 

 

Guess you like

Origin blog.csdn.net/gdjlc/article/details/93381137