Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use flask Jinja2

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "how to use flask Jinja2". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. What is Jinja2 template engine

To understand jinja2, you need to understand the concept of templates. Templates are widely used in the web development of Python. It can effectively separate business logic from page logic, making the code more readable and easier to understand and maintain.

To put it simply, a template is a file that contains the dynamic part of the placeholder variable. After dynamic assignment, the template file is returned to the user. -- > can be understood as rendering

A simple template is included with python, which is provided by string.

> import string > a = string.Template ('$who is $role') > a.substitute (who='daxin',role='Linux') 'daxin is Linux' > a.substitute (who='daxin',role='cat')' daxin is cat' >

The template functionality that comes with Python is so limited that it won't be possible if we want to use control statements, expressions, inheritance and other functions in the template.

At present, jinja2 and mako are the most commonly used template systems.

Jinja2 introduction

Jinja2 is a template system developed by the authors of Flask. At first, it is a template engine imitating django template, which provides template support for Flask. It is widely used because of its flexibility, speed and security.

Advantages of jinja2

Jinja2 is widely used because it has the following advantages:

More flexible than Template,jinja2, it provides control structures, expressions, inheritance, and so on.

There is only a control structure relative to Mako,jinja2, so it is not allowed to write too much business logic in the template.

Jinja2 performs better than Django templates.

The readability of Jinja2 templates is great.

Install jinja2

Since jinja2 is a third-party module, it needs to be installed first

Whether the pip3 install jinja2 test template is successfully installed python-c "import jinja2" # if no error is reported, the installation is successful # you must use double quotation marks "jinja2 syntax

As a template system, it also provides special syntax, and once we write it according to the syntax it supports, we can use the jinja2 module to render.

Basic grammar

In jinja2, there are three grammars:

Control structure {%}

Variable value {

{}}

Note {#}

Here is a simple example of jinja2

{# This is jinja code {% for file in filenames%}... {% endfor%} #}

As you can see, the for loop is used in a similar way to Python, but without the colon at the end of the sentence, and you need to use endfor as the end. In fact, in jinja2, if is the same, with endif at the end.

Jinja2 variable

The jinja2 template uses the {{}} syntax to represent a variable, which is a special placeholder. When rendering with jinja2, it populates / replaces these special placeholders, and jinja2 supports all Python data types in python, such as lists, fields, objects, and so on.

This is a dicectory: {{mydict ['key']}}

This is a list: {{mylist [3]}}

This is an object: {{myobject.something ()}}

Filters in jinja2

Variables can be modified through "filters", which can be understood as built-in functions and string handling functions in jinja2.

Commonly used filters are:

The filter name indicates that the safe render value does not escape capitialize converts the first letter of the value to uppercase Other subletters convert values to lowercase lower, convert values to lowercase upper, convert values to uppercase title, convert the first letter of each word in the value to uppercase trim, remove the leading and trailing spaces of the value, delete all HTML tags in the value before striptags rendering, delete join splicing multiple values into strings, replace strings, round rounds numbers by default, and you can also use parameters to control int to convert values to integers.

So how do you use these filters? You only need to split the variable with a pipe (|), multiple filters can be chained, and the output of the previous filter will be used as the input of the latter filter.

{{'abc' | captialize}} # Abc {{' abc' | upper}} # ABC {{'hello world' | title}} # Hello World {{"hello world" | replace (' world','daxin') | upper}} # HELLO DAXIN {{18.18 | round | int}} # 18jinja2

The if statement in jinja2 is similar to the if statement in Python, it also has many structures, such as single branch, multi-branch and so on. The difference is that the conditional statement does not need to end with a colon, while the end control statement needs to use the endif keyword.

{% if daxin.safe%} daxin is safe. {% elif daxin.dead%} daxin is dead {% else%} daxin is okay {% endif%} jinja2's for loop

The for loop in jinja2 is used to iterate over Python's data types, including lists, tuples, and dictionaries. There is no while loop in jinja2.

Iteration list

{% for user in users%} {{user.username | title}} {% endfor%}

Iterative dictionary

{% for key, value in my_dict.iteritems ()%} {{key}} {{value}} {% endfor%}

Of course, you can also add an else statement to execute the loop after the loop has been executed correctly

In the for loop, jinja2 also provides some special variables to get the current traversal state:

Variable describes the index of the current iteration of loop.index (starting at 1) the index of the current iteration of loop.index0 (starting at 0) whether loop.first is the first iteration, returns whether boolloop.last is the last iteration, returns the number of items in the boolloop.length sequence loop.revindex to the number of times the loop ends (starting from 1) loop.revindex0 to the number of times the loop ends (starting at 0) jinja2

Macros are similar to functions in Python, where we define behavior and pass parameters, just like functions in Python.

The keyword to define a macro in a macro is macro, followed by the name and parameters of the macro, etc.

{% macro input (name,age=18)%} # the default value of the parameter age is 18 {% endmacro%}

The calling method is also similar to that of Python

{{input ('daxin')}}

{{input ('daxin',age=20)}}

Inheritance of jinja2 and Super function

The most powerful part of jinja2 is template inheritance. Template inheritance allows us to create a basic (skeleton) file, other files inherit from the skeleton file, and then modify it where we need it.

In the skeleton file of jinja2, the content contained in it can be modified by using the block keyword.

Take the following skeleton file base.html as an example:

{% block head%} {% block title%} {% endblock%}-My Webpage {% endblock%} {% block content%} {% endblock%} {% block footer%} This is javascript code {% endblock%}

Four block are defined here, namely: head,title,content,footer. So how to inherit and replace variables? Pay attention to the following file

{% extend "base.html"%} # inherits the contents of the base.html file {% block title%} Dachenzi {% endblock%} # Custom title section {% block head%} {{super ()}} # to get the original information. Inherit {color: # FFFFFF} {% endblock%} # different inheritance that he does not modify

The PS: super () function means to get the original content defined in the block block.

Rendering with jinja2

There is a class called Enviroment in the jinja2 module, and an instance of this class is used to store configuration and global objects, and then load templates from the file system or other locations.

Basic usage

Most applications bump into an Environment object during initialization and use it to load templates. Environment supports two loading methods:

PackageLoader: packet loader

FileSystemLoader: file system loader

PackageLoader

The easiest way to load a document using the package loader is as follows:

From jinja2 import PackageLoader,Environmentenv = Environment (loader=PackageLoader ('python_project','templates')) # create a package loader object template = env.get_template (' bast.html') # get a template file template.render (name='daxin',age=18) # render

Where:

The two parameters to PackageLoader () are the name of the python package and the name of the template directory.

Render (): accept variables and render the template

Get_template (): gets a specific file in the template directory.

FileSystemLoader

File system loader does not need template files to be stored in a Python package, and can directly access files in the system.

That's all for the content of "how to use flask Jinja2". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report