Python learning-use templates

The web framework saved us from WSGI. Now, we only need to continue to write the function, bring the URL, you can continue the development of Web App.

However, Web App is not only processing logic, but the page displayed to the user is also very important. Return a string containing HTML in the function. A simple page is okay. But, think about the more than 6000 lines of HTML on the Sina homepage. Are you sure you can write it in the Python string correctly? I can't do it anyway. (Hahaha, it leads to the necessity of templates)

As the saying goes, Python engineers who don't understand the front-end are not good product managers. Students with experience in web development know that the most complicated part of a web app is in the HTML page. HTML must not only be correct, but also beautified by CSS, coupled with complex JavaScript scripts to achieve various interactive animation effects. In short, it is very difficult to generate HTML pages.

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

To use a template, we need to prepare an HTML document in advance. This HTML document is not ordinary HTML, but embeds some variables and instructions . Then, after replacing it according to the data we passed in , we get the final HTML and send it to the user.

Insert picture description here

Note that a render_template is returned here to render the template

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

The function of Python processing URL is C: Controller, Controller is responsible for business logic, such as checking whether the user name exists, taking out user information and waiting; (keyword: logic)

The template that contains the variables { {name }} is V: View. View is responsible for the display logic. By simply replacing some variables, the final output of View is the HTML that the user sees. (Keyword: display)

Where is the Model in MVC? The Model is used to pass to the View , so that when the View replaces the variable, it can retrieve the corresponding data from the Model . (Keyword: data)

In the above example, Model is a dict:

{
    
    'name':'Michael'}

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

Now, let's rewrite the example of directly outputting the string as HTML last time with the high-end and high-end MVC mode:

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 achieve template rendering . Similar to web frameworks, there are many templates for Python. The default template supported by Flask is jinja2, so let's follow jinja2 directly:

$ pip install jinja2

Then, start writing the jinja2 template:


The template used to display the home page of home.html :

<html>
<head>
  <title>Home</title>
</head>
<body>
  <h1 style="font-style:italic">Home</h1>
</body>
</html>

The template
used to display the login form in form.html :

<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.htmlSign-in
successful template:

<html>
<head>
  <title>Welcome, {
    
    {
    
     username }}</title>
</head>
<body>
  <p>Welcome, {
    
    {
    
     username }}!</p>
</body>
</html>

What about the login failed template? We added a little judgment to form.html and reused form.html as a template for login failure. (Reuse is important)

Finally, be sure to put the template in the correct templates directory. Templates and app.py are in the same level directory:
Insert picture description here
start python app.py and see the page effect using the template:
(The code was wrong before, and the default prompt is not Username , After the change, the {symbol is still displayed. It can only be displayed after restarting the server, so not only do you need to change the code, but also restart the server?)
Insert picture description here

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

Another big advantage of using a template is that it is easy to change the template, and after the change is saved, you can refresh the browser to see the latest effect. This is really important for the former engineers who debug HTML, CSS and JavaScript. Up.

In the Jinja2 template, we use { {name }} to indicate a variable that needs to be replaced. In many cases, instruction statements such as loops and conditional judgments are also needed. In Jinja2, {%… %} is used to represent instructions.
For example, loop output page number

{
    
    % for i in page_list %}
	<a href="/page/{
    
    { i }}">{
    
    {
    
     i }}</a>
{
    
    % endfor %}

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

In addition to Jinja2, common templates include:

  • Mako: Use a template of <%… %> and ${xxx};

    Cheetah: Also use a template of <%… %> and ${xxx};

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

summary

With MVC, we have separated Python code and HTML code. Put all HTML code in the template, which makes it more efficient to write.

Guess you like

Origin blog.csdn.net/qq_44787943/article/details/112638859