Flask Web development-flask Template 1-template mechanism &JINJA2 engine

Source: Internet
Author: User

Excerpt from Parti Chapter3, this chapter mainly talk about the template work principle, here is Jinja2 this template, also mentioned Flask-bootstrap and flask-moment two plug-ins, The former made some encapsulation for flask using bootstrap, while the latter did some encapsulation on moment.js. More content, estimate separate to engage.

The meaning of template existence

The code with high maintainability is well-structured and tidy.

When a user registers an account with the website, he fills in the form with the email and password, and clicks the submit button. On the server side, you receive a request containing this data, which is then distributed by flask to the corresponding view function. The view function generates two tasks here, first adding a new user to the database, and then returning a response to the user's browser. These two tasks can be referred to as businesslogic and Reporting logic (presentationlogic), respectively.

Mixing the two logic together can lead to code clutter and difficult maintenance. You can imagine the complexity of generating complex HTML pages and embedding data directly in your code. Moving report logic into template processing can improve the maintainability of your application.

A template is actually a text with some dynamic parts that contain variables that can be known when the request context is in the content. To replace these variables with actual values, the process of eventually generating a response string is called rendering. Flask uses a powerful JINJA2 to handle render template tasks.

JINJA2 Template engine

A simple Jinja2 template,index.html:

 

is a fixed string that returns the string directly. Look at the slightly more complicated, user.html:

 

With a dynamic part, which name is a variable, the response will change with it.

Render Template

Flask default to the application root directory under the Templates folder to find the appropriate template, first put the above two simple templates in this folder, and then modify the previously written hello.py:

From flask import flask, render_template# ... @app. Route ('/index ') def index ():    return render_template (' index.html ' ) @app. Route ('/user/<name> ') def user (name):    return render_template (' user.html ', name=name)

Note: The above is the 3a tag code on GitHub

FLASK provides a render_template function that can be used with JINJA2, whose first argument is the template name, followed by a variable value in the template, passed in as a key/value. Key is the variable name that is written in the template.

Variables in the template

{{ name }}This structure represents a reference to a variable that tells the template engine that the value in it needs to be fetched in the data provided when the template is rendered.

JINJA2 can recognize many types, even including lists, dictionaries, and objects. Such as:

<p>a value from a dictionary: {{mydict[' key ')}}.</p><p>a value from a list: {{mylist[3]}}.</p> <p>a value from a list, with A variable index: {{Mylist[myintvar]}}.</p><p>a value from a object ' s me Thod: {{myobj.somemethod ()}}.</p>

Variables can be further modified by the filter, which is placed after the variable separated by a delimiter. For example, the following template indicates that the variable is capitalized by the first letter:

Hello, {{name|capitalize}}

Common filters are as follows:

    • Safe does not escape incoming values
    • Capitalize incoming value first letter uppercase, other lowercase
    • Lower incoming values all to uppercase
    • Upper incoming values are all converted to lowercase
    • Title The first letter of each word in the incoming value is capitalized
    • Trim incoming value before and after spaces are deleted
    • Striptags all HTML tags in the incoming value are deleted

It is important to mention that, for security reasons, the safe JINJA2 defaults to escaping the values in the variable, such as the value, which is rendered as a result of the &lt;h1&gt;Hello&lt;/h1&gt; inline label invalidation, and the filter if it is necessary to display the inline tag safe .

Note: For locations that cannot be trusted, do not use safe , such as the form values that users fill in.

More filters can refer to JINJA2 official documentation

Control structure

JINJA2 provides several control structures to change the rendering process of the template. Here are some of the more common ones.

Add conditional controls to the template:

{% if user%}    Hello, {{User}}! {% Else%}    Hello, stranger!. {% ENDIF%}

A list element is looped in the template:

<ul>    {% for comment in comments%}        <li>{{comment}}</li>    {% endfor%}</ul>

JINJA2 supports macros, similar to functions in the Pyhton code:

{% Macro render_comment (comment)%}    <li>{{comment}}</li>{% endmacro%}<ul>    {% for comment in comments%}        {{render_comment ( Comment)}}    {% endfor%}</ul>

To increase the reuse of macros, you can put macros into separate files and then introduce them in the template:

{% import ' macros.html ' as macros%}<ul>    {% for comment in comments%}        {{macros.render_comment (comment)}}< c9/>{% endfor%}</ul>

Some of the code in the template repeats itself in different places, save the part as a file, include come in as needed, and avoid repeating the writing:

{% include ' common.html '%}

Another important way to increase reusability is template inheritance, similar to the inheritance of classes in Python code. Define a basic template first:

' base.html ':

The block elements in the tag can be changed in the inherited template. A chunk named above appears head,title,body . Attention title is defined in the head . Look at an example of inheriting this template:

{% extends "base.html"%} {% block title%} index{% endblock%}{% block head%}    {{super ()}}    <style>    </style>{% endblock%}{% block body%} 

extendsKeyword declaration This template is inherited from base.html , followed by three newly defined chunks, the chunk name and the definition order correspond to the basic template. Note that in the basic template the head chunks are content, and the use super() method preserves the original content.

There will be more information about how the templates are actually used in the future.

Flask Web development-flask Template 1-template mechanism &JINJA2 engine

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.