Tutorial on using HTML templates in Python

Source: Internet
Author: User

Tutorial on using HTML templates in Python

This article mainly introduces how to use HTML templates in Python. HTML templates are also a basic function of Python frameworks. For more information, see

The Web framework saves us from WSGI. Now, we only need to constantly Write Functions and add URLs to continue the development of Web apps.

However, Web apps are not only processing logic, but also pages displayed to users. Return a string containing HTML in the function. A simple page can also be used. However, consider the HTML of more than 6000 lines on the Sina homepage, are you sure you can write it correctly in Python strings? I cannot do it anyway.

As the saying goes, Python engineers who do not know the frontend are not good product managers. All those who have Web development experience understand that the most complex part of a Web App is the HTML page. HTML should not only be correct, but also be beautified through CSS, coupled with complex JavaScript scripts to achieve various interactions and animation effects. In short, it is difficult to generate HTML pages.

Since it is unrealistic to spell strings in Python code, the template technology has emerged.

To use the template, we need to prepare an HTML document in advance. This HTML document is not a common HTML document, but embedded with some variables and instructions. Then, based on the data we input, after replacement, get the final HTML and send it to the user:

This is the legendary MVC: Model-View-Controller. The Chinese name is "Model-View-Controller ".

Python's URL Processing Function is C: Controller, which is responsible for business logic, such as checking whether the user name exists and retrieving user information;

The template that contains the variable {name} is V: View. View is responsible for the display logic. by simply replacing some variables, View outputs the HTML that you see.

Where is the Model in MVC? The Model is used to pass to the View, so that when the View replaces the variable, the corresponding data can be retrieved from the Model.

In the above example, the Model is a dict:

{'Name': 'Michael '}

Only because Python supports keyword parameters, many Web frameworks allow the input of keyword parameters, and then assemble a dict inside the framework as the Model.

Now, let's rewrite the previous example of directly outputting a string as HTML in the MVC mode of the high-end atmosphere:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

From flask import Flask, request, render_template

 

App = Flask (_ name __)

 

@ App. route ('/', methods = ['get', 'post'])

Def home ():

Return render_template('home.html ')

 

@ App. route ('/signin', methods = ['get'])

Def signin_form ():

Return render_template('form.html ')

 

@ App. route ('/signin', methods = ['post'])

Def signin ():

Username = request. form ['username']

Password = request. form ['Password']

If username = 'admin' and password = 'Password ':

Return render_template('signin-ok.html ', username = username)

Return render_template('form.html ', message = 'bad username or password', username = username)

 

If _ name _ = '_ main __':

App. run ()

Flask uses the render_template () function to render the template. Similar to the Web framework, there are many Python templates. The default template supported by Flask is jinja2. Therefore, we should install jinja2 directly:

?

1

$ Easy_install jinja2

Then, write the jinja2 template:

?

1

Home.html

Template used to display the homepage:

?

1

2

3

4

5

6

7

8

9

10

11

<Html>

<Head>

<Title> Home </title>

</Head>

<Body>

<H1 style = "font-style: italic"> Home

</Body>

</Html>

 

 

Form.html

The template used to display the logon form:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<Html>

<Head>

<Title> Please Sign In </title>

</Head>

<Body>

{% If message %}

<P style = "color: red" >{{ message }}</p>

{% Endif %}

<Form action = "/signin" method = "post">

<Legend> Please sign in: </legend>

<P> <input name = "username" placeholder = "Username" value = "{username}"> </p>

<P> <input name = "password" placeholder = "Password" type = "password"> </p>

<P> <button type = "submit"> Sign In </button> </p>

</Form>

</Body>

</Html>

 

Signin-ok.html

Template for Successful Logon:

?

1

2

3

4

5

6

7

8

<Html>

<Head>

<Title> Welcome, {username }}</title>

</Head>

<Body>

<P> Welcome, {username }}! </P>

</Body>

</Html>

What about the logon Failure template? In form.html, we added the conditional condition to reuse form.html as a logon Failure template.

Finally, you must put the template in the correct templates directory. the templates and app. py are in the same directory:

Start python app. py to see the page effect of the template:

Through MVC, we can process M: Model and C: Controller in Python code, while V: View is handled through templates. In this way, we have successfully separated the Python code from the HTML code to the maximum extent.

Another major benefit of using a template is that the template can be easily changed. After the template is changed and saved, refresh the browser to see the latest results, this is too important for front-end engineers who debug HTML, CSS, and JavaScript.

In the Jinja2 template, {name} is used to represent a variable to be replaced. In many cases, commands such as loop and condition judgment are also required. In Jinja2, {%... %} is used to indicate the command.

For example, the page number of the loop output:

?

1

2

3

{% For I in page_list %}

<A href = "/page/{I}" >{{ I }}</a>

{% Endfor %}

If page_list is a list: [1, 2, 3, 4, 5], the template above outputs five hyperlinks.

In addition to Jinja2, common Templates include:

Mako: Use a template of <%... %> and $ {xxx;

Cheetah: it is also a template with <%... %> and $ {xxx;

Django: Django is a one-stop framework with built-in templates {%... %} and {xxx.

Summary

With MVC, we separate the Python code from the HTML code. Put all HTML code in the template to make it more efficient to write.

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.