Some time ago, we needed to do a template processing job. Because we need to perform logic processing in the template, simple replacement of tuples and keywords can no longer meet the requirements. Therefore, select the python 3rd template engine to implement this function. At present, many templates are mainly used for Mako and Jinja. After comparison, I found that Jinja's template engine is similar to Django's syntax, so I chose Jinja as my template engine.
First, I downloaded the source code package on the Jinja official website and installed it. Then I read the official documents and tested some simple functions to prepare for future development.
Now let's start a simple operation:
Start and assign values to the template in Python.
ENV = environment (loader = packageloader ('mbtest', 'templates') # mbtest is a module in which content can be written at will. tempaltes is the template folder name, jinja templates can be used to list templates.
TPL = env. get_template ('B2B-product. php') # Template Name
Randarticle = rand_article (randnum)
Keyword = 'test'
Minfo = []
Displayinfo = {'ptitle': ptitle, 'pdescription': pdescription} # use a dictionary as an object in Python. The key in the object is the property of the object, and Val is the property value of the object.
Minfo. append (displayinfo)
Tplcontent = TPL. Render (minfo = minfo, keyword = keyword, randarticle = randarticle) # template variable assignment
Template processing:
Here, we simply assign values to the template, and output the template cyclically.
TPL. Render (minfo = minfo, keyword = K [1], randarticle = randarticle)
The keyword output in the template is in the format of {keyword {{}}
The statement output in the template is similar to that in Django syntax. If you are familiar with Django, you will feel very friendly.
{% For K in minfo %}
{K. ptitle }}
{K. pdescription }}
{% Endfor %}
This is just a simple template operation. I will update some more complex applications in the future. You can also refer to the official documentation.