python template rendering jinja2 - python Web

Keywords: Python Java Web Development

python template rendering jinja2 - python web (3)

​      Jinja2 is a fast, expressive and extensible template engine. It was written by werkzueg author Armin ronacher (people used to call him mitsuhiko )Development, used for data rendering of python web html pages, flush with jsp of java servlet. Jinja2 makes it possible to use python syntax in pages and translate them into html pages; Another function of jinja2 is to render word templates for practical applications such as contract signing.

3.1 basic syntax:

     Note that all control structures must end with the {% end keyword%}.

  • Variable value {{python_code}}
  • Control structure {% python_code%}
  • Template notes {# Python # OCDE #}
3.2 template rendering:

​      The paths in the template are relative to the root path of the initialization template, so as to load the html file location and render the html page with dictionary data. Assume that the file is flush with the templates Directory:

from jinja2 import Environment
from jinja2 import FileSystemLoader

# Configuring jinja templates
template_path = os.path.join(os.path.dirname(__file__), "templates")
jinja_env = Environment(
    loader=FileSystemLoader(template_path), autoescape=True

def save(dst, data):
    with open(dst, 'w') as fp:

# Rendering template, combined with werkzueg, can return a Response
# This example outputs the rendered html page to the file out.html
def render_template(template_name, **context):
    t = jinja_env.get_template(template_name)
    # t.render(context) returns a str string
    data = t.render(context)
    save('./out.html', data)
3.3 jinja2 control structure:

The correctness of python syntax must be guaranteed, otherwise the template rendering will report an error

(1) Select structure:

a) data:

session = {"user": {"id": 1, "name": "test1"}}
render_template("test_if.html", sessionScope=session)

b) formwork:

{# Two branch selection example, multiple branches are the same python #}
{% if sessionScope.get("user", False) %}
    <li>Personal Center accout</li>
    <li>cancellation logout</li>
{% else %}
    <li>Sign in login</li>
    <li>register register</li>
{% endif %}

(2) Cycle structure:

a) Data:

goods_lst = [
    {"id":1 , "name": "test_for1"},
    {"id":2 , "name": "test_for2"}
render_template("test_for.html", goodslist=goods_lst)

b) formwork:

<!-- test_for.html -->
    {% for goods in goodslist %}
    {# This is not necessary if, Explain usage #}
    {% if loop.first %}
    {% endif %}
        {# Objects can be clicked and dictionary keywords can be keyed #}
        <td>{{ goods['id'] }}</td>
        <td>{{ goods['name'] }}</td>
    {% endfor %}

Special loop variables for jinja2:

loop.index / loop.index0The index of the current iteration starts from 1 by default (index0 starts from 0)
loop.revindex / loop.revindex0Reverse iteration index, range [len, 1] / [len-1, 0]
loop.first / loop.lastBoolean value, whether to start / end the iteration
loop.lenthIteration list length
3.4 jinja2 filter

​      The data dictionary passed through context only supports get, keys, values, items, iterkeys, itervalues, iteritems
__ getitem__,__ contain__ These python methods, the latter two are click and in keywords respectively; If you want to perform some operations when the template variable values, you need to use the function, which is the filter option provided by the template. If you want to avoid these operations, you need to preprocess the data in the python code.

(1) Template built-in filter:

typeFunction namefunction
character stringsafe
capitalize / title
lower / upper
Disable escape
Initial capitalization / word initial capitalization
To lowercase / to uppercase
String inversion
Delete HTML tags
String truncation
Take the first element
Take the last element
Fetch list length
List summation
List sorting (you don't have to do it here)
numerical valueint / round

(2) Filter call:

The general template syntax is {% filter%}, and the pipeline operation can also be performed when the template value is taken. The pipeline supports chain operation:

{# Block syntax #}
{% filter upper%}
    edg niubi
{% endfilter %}
{# Pipe take #}
{{ edg niubi | title | reverse }}

(3) Custom filter:

Jinja2 supports the transfer of custom python functions into the jinja2 environment for calling. These situations can generally be handled in advance to avoid:

def multiple(a, b):
    return a * b

# Register custom filters
jinja_env['multi'] = multiple

# Template call
# {{ 3 | multi:2 }}
3.5 template reuse and inheritance:

​      For a large website, the theme structure of the website is the same. jinja2 supports the reuse of templates, which can make the html pages of each function module pay more attention to their own functions. The template syntax uses the block keyword to reserve the content to be filled, and uses the extend keyword to inherit the html code of the basic template.

(1) Foundation formwork:

<!-- front/basic.html -->
		<!-- Reserved Title Filling-->
		<title>{% block title_head %} {% endblock %}</title>
		<link href="xxxx.css" rel="stylesheet"/>
		<script type="text/javascript" src="xxx.js"></script>
			This is header!
		<!-- Reserved body content filling-->
		{% block main_body %}
		{% endblock %}

(2) Template filling:

<!-- front/login.html -->

{% extends 'front/basic.html' %}

{% block title_head %} Login page {% endblock %}

<!-- Fill 3)Content in -->

{% block main_body %}
	Login function page
{% endblock %}

(3) Styles and functions of specific pages:

Fill in the head tag directly, use the super keyword to inherit the original content, and define your own style and js:

{% block head %}
    {{  super()  }}        # Used to obtain the original information
    <style type='text/css'>
    .important { color: #FFFFFF }
	 	console.log("This is Login Page");
{% endblock %}   

​      After introducing the basic content related to Python web template rendering, jinja2 can also be combined with docxtpl to generate word template, which is very practical; The control layer werkzueg and the data layer Python DB API have all been introduced. In the next article, an example similar to spring MVC will be used to synthesize these contents.

Posted by Dark Phoenix on Mon, 08 Nov 2021 09:50:34 -0800