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 config.py 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: fp.write(data) # 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:
<!--test_if.html--> {# Two branch selection example, multiple branches are the same python #} <ul> {% 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 %} </ul>
(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 --> <table> {% for goods in goodslist %} {# This is not necessary if, Explain usage #} {% if loop.first %} <tr> <th>ID</th> <th>Name</th> </tr> {% endif %} <tr> {# Objects can be clicked and dictionary keywords can be keyed #} <td>{{ goods['id'] }}</td> <td>{{ goods['name'] }}</td> </tr> {% endfor %} </table>
Special loop variables for jinja2:
variable | describe |
---|---|
loop.index / loop.index0 | The index of the current iteration starts from 1 by default (index0 starts from 0) |
loop.revindex / loop.revindex0 | Reverse iteration index, range [len, 1] / [len-1, 0] |
loop.first / loop.last | Boolean value, whether to start / end the iteration |
loop.lenth | Iteration 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:
type | Function name | function |
---|---|---|
character string | safe capitalize / title lower / upper reverse striptags truncate | Disable escape Initial capitalization / word initial capitalization To lowercase / to uppercase String inversion Delete HTML tags String truncation |
list | first last length sum sort | Take the first element Take the last element Fetch list length List summation List sorting (you don't have to do it here) |
numerical value | int / 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 --> <html> <head> <!-- Reserved Title Filling--> <title>{% block title_head %} {% endblock %}</title> <link href="xxxx.css" rel="stylesheet"/> <script type="text/javascript" src="xxx.js"></script> </head> <body> <header> This is header! </header> <!-- Reserved body content filling--> {% block main_body %} {% endblock %} </body> </html>
(2) Template filling:
<!-- front/login.html --> {% extends 'front/basic.html' %} {% block title_head %} Login page {% endblock %} <!-- Fill 3)Content in --> {% block main_body %} <main> Login function page </main> {% 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 } </style> <script> console.log("This is Login Page"); </script> {% 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.