Web development based on hi-nginx (python) -- using jinja2 template engine, hi-nginxjinja2
The use of the template engine is inevitable and necessary in web development. The hi. py framework uses jinja2 as the template engine.
To use the jinja2 engine provided by hi. py, you must first introduce it:
from hi import hi,template
Then use it:
1 @ app. route (R' ^/template /(? P <name> \ w + )/(? P <age> \ d + )/? $ ', ['Get']) 2 def tpl (req, res, param): 3 param ['title'] = 'jinja2 test' 4 tpl_engine = template (OS. path. join (OS. getcwd (), 'python/templates') 5 res.content(tpl_engine.file_render(' B .html ', param) 6 res. status (200)
To create a template instance, you need a parameter that specifies the directory of the engine search template file. In the above Code, it is the python/templates folder under the install directory of hi-nginx.
Then, prepare the data, use dict to collect the data, and use the file_render method to output the string content by specifying the template file and data dict.
If you are not using a template file but a template string, use the string_render method. Its first parameter indicates a string template.
In the example, the B .html content of the template file is as follows:
1 {% extends 'a.html '%} 2 {% block body %} 3 {super ()}} 4 inherit from 5 {name }}is {age} years old.6 {% endblock %}
The template inheritance function in jinja2 is used. For details, see the first line. For this reason, there is also a template file a.html:
<Html>
In this example, the Chinese content already appears. Therefore, UTF-8 encoding is required. Hi-nginx fully supports python3!