The use of template engines is unavoidable 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 first need to introduce it:
from Import Hi,template
Then it is used:
1@app. Route (R'^/template/(? p<name>\w+)/(? p<age>\d+)/?$',['GET'])2 defTPL (req,res,param):3param['title']='JINJA2 Test'4Tpl_engine = Template (Os.path.join (OS.GETCWD (),'python/templates'))5Res.content (Tpl_engine.file_render ('b.html', param))6Res.status (200)
Creating a template instance requires a parameter that specifies the directory where the engine searches for the templates file, which in the code above is the Python/templates folder in the Hi-nginx installation directory.
The data is then prepared, the data is collected using Dict, and the File_render method is used to output the string content by specifying the template file and the data dict.
If you are not using a template file, but a template string, use the String_render method, whose first parameter refers to a string template.
In the example above, the template file b.html content is as follows:
1 {% extends ' a.html ' %}2{% block body%}3 {{super ()} }4 inherit 5{{name }} is {{Years }}. 6 {% Endblock%}
The template inheritance function in JINJA2 is used, see the first line. Therefore, there is also a template file a.html:
<HTML> <Head><title>{{title}}</title></Head> <Body>{% block body%}<P>hello:{{name}},you is {{age}} years old.</P> <P>The loader is responsible for loading templates from resources such as file systems</P>{% Endblock%}</Body></HTML>
In this case, the Chinese content already appears. Therefore, you need to use UTF-8 encoding. Hi-nginx has fully supported Python3, so, enjoy Chinese!
Hi-nginx-based Web development (python)-Using the JINJA2 template engine