[11] Flask tutorial template

  • Basic use
  • Filter & custom filter
  • Control block
  • Macro, inheritance, contain
  • Flask template-specific variables and methods
  • web form
  • CSRF

learning target

  • Capable of writing variable code blocks and code block control format jinja2
  • Be able to write the value of a dictionary in the template, the list of
  • Possible to write a custom filter array inverted (can be used alone mode)
  • Flask able to say three ways in template code reuse
  • Able to use the code to achieve the function template inheritance
  • Can say Flask variables and functions that can be used directly in the template
  • Flask-WTF can be used to achieve the extended registration form
  • CSRF attacks can say the principle of

 

A, Jinja2 template engine Introduction

template

In the previous example, the primary effect is to function in response to the view generation request, which is the most simple request.

In fact, the view function has two effects: the processing business logic and return a response content .

In large applications, business logic and presentation content together, it will increase the complexity and maintenance costs of the code.

This learned template section, i.e., its role is to assume the role of another view of a function that returns a response content.

  • In fact, the template is a text file containing the response , which is represented by a placeholder (variable) dynamic part that tells the template specific values obtained from the data engine needs to be used in
  • Substitution variables with real values, and then returns the resulting string, a process called "rendering"
  • Flask is Jinja2 use this template engine to render template

The benefits of using templates:

  • The view function is only responsible for processing service logic and data (business logic terms)
  • And then take the template data on display function result view (view showing aspects)
  • Clear code structure, low coupling

Jinja2

Two concepts:

  • Jinja2: Python is a widely used template engine , is implemented by Python template language , his design ideas from Django template engine, and expanded its syntax and a powerful set of features that are built-in templates Flask language.
  • Template language: is a document designed to automatically generate simple text format, in the template language, usually some variables passed to the template, replacing the template of a specific location on a pre-defined placeholder variable name .

Render the template function

  • Flask provided  render_template  function encapsulates the template engine
  • The first parameter is the file name render_template function template, the latter parameters are key-value pairs, represent the true value of the variable in the corresponding template.

use

  • {} {} Represent variable name, which is called the syntax {} {} block variables
<h1>{{ post.title }}</h1>

Jinja2 template variables Python code blocks may be of any type or an object, as long as it can be converted to the Python str () method can be a string , for example, an element may be displayed in a list or dictionary of the following ways :

{{your_dict['key']}}
{{your_list[0]}}
  • Control block defined by {} %%, the language can achieve some level of functionality, such as loops or if statements
{% if user %}
    {{ user }}
{% else %}
    hello!
<ul>
    {% for index in indexs %}
    <li> {{ index }} </li>
    {% endfor %}
</ul>

Note

  • {##} using the annotation, annotation content can not be rendered in html
{# {{ name }} #}

 

Second, the use of templates

  • Under the project to create  templates a folder to hold all of template files, and create a template html file in the directory temp_demo1.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
我的模板html内容
</body>
</html>
  • Set templates folder properties in order to be able to have smart tips in the code

  • Setting language html template in order to have smart tips in html

  • Create a view function, carry out the template content rendering return
@app.route('/')
def index():
    return render_template('temp_demo1.html')

 

访问:http://127.0.0.1:5000/ 运行测试

  • 代码中传入字符串,列表,字典到模板中
@app.route('/')
def index():
    # 往模板中传入的数据
    my_str = 'Hello 博客园'
    my_int = 10
    my_array = [3, 4, 2, 1, 7, 9]
    my_dict = {
        'name': 'xiaoming',
        'age': 18
    }
    return render_template('temp_demo1.html',
                           my_str=my_str,
                           my_int=my_int,
                           my_array=my_array,
                           my_dict=my_dict
                           )

 

  • 模板中代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
我的模板html内容
<br/>{{ my_str }}
<br/>{{ my_int }}
<br/>{{ my_array }}
<br/>{{ my_dict }}

</body>
</html>

 

  • 运行效果
<!DOCTYPE html>

我的模板html内容 
Hello 黑马程序员 
10 
[3, 4, 2, 1, 7, 9] 
{'name': 'xiaoming', 'age': 18}

 

  • 相关运算,取值
<br/> my_int + 10 的和为:{{ my_int + 10 }}
<br/> my_int + my_array第0个值的和为:{{ my_int + my_array[0] }}
<br/> my_array 第0个值为:{{ my_array[0] }}
<br/> my_array 第1个值为:{{ my_array.1 }}
<br/> my_dict 中 name 的值为:{{ my_dict['name'] }}
<br/> my_dict 中 age 的值为:{{ my_dict.age }}

 

  • 结果
my_int + 10 的和为:20 
my_int + my_array第0个值的和为:13 
my_array 第0个值为:3 
my_array 第1个值为:4 
my_dict 中 name 的值为:xiaoming sort:列表排序
 

Guess you like

Origin www.cnblogs.com/zeug/p/11367486.html
Recommended