This article mainly introduces how to use HTML templates in Python. HTML templates are also a basic function in various Python frameworks, if you need it, you can refer to the Web framework to save 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:
from flask import Flask, request, render_templateapp = 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:
$ easy_install jinja2
Then, write the jinja2 template:
home.html
Template used to display the homepage:
Home Home form.html
The template used to display the logon form:
Please Sign In {% if message %} {{ message }}
{% endif %} signin-ok.html
Template for successful logon:
Welcome, {{ username }} Welcome, {{ username }}!
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:
{% for i in page_list %} {{ i }}{% 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.