Hi-nginx-based Web development (python)-Using the JINJA2 template engine

Source: Internet
Author: User

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

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.