Web development based on hi-nginx (python) -- using jinja2 template engine, hi-nginxjinja2

Source: Internet
Author: User

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!

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.