Today, the lesson of Flask has entered the fifth lecture. I started from the most basic point. I believe you have learned it well
Today we will focus on two aspects: template context and template inheritance
Template context
In the previous section, we learned that Jinja2 provides many control structures to change the rendering process of templates.
{% %}yes Jinja2 Control statements in, {{ }}yes Jinja2 Variables in, {# #}It's a comment.
Typically, template is called when rendering a template_ The render() function passes in variables to the template. In addition, you can use set and with to define variables
set statement:
In the template, you can use the set statement to define variables. Examples are as follows:
{% set username='Cat picking class' %} <p>user name:{{ username }}</p>
Once this variable is defined, it can be used in subsequent code, which is similar to the global variable defined by Python.
with statement:
The variables defined by the with statement can only be used in the with statement block. Beyond this code block, they can no longer be used. The example code is as follows:
{% with classroom = 'Cat picking class' %} <p>Class:{{ classroom }}</p> {% endwith %}
The with statement does not have to be followed by a variable. You can define an empty with statement. Later, the variables defined through set in the with block can only be used in the with block,
Similar to local variables in Python
{% with %} {% set classroom = 'Cat picking class' %} <p>Class:{{ classroom }}</p> {% endwith %}
Common template built-in global variables
config | Current configuration object |
request | Current request object |
session | Current session object |
g | Global variable bound to the request |
Use the built-in global variable session to determine whether the user logs in
If the user logs in, the user name will be displayed, otherwise the prompt 'please log in first!'
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>User login</title> </head> <body> {% if session['log_in'] %} welcome{{session['username']}}Sign in {% else %} Please log in first! {% endif %} </body> </html>
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>User login</title> </head> <body> <form action="" method="post"> <div> <label for="username">user name</label> <input type="text" id="username" name="username" value=""> </div> <div> <label for="password">dense code</label> <input type="password" id="password" name="password" value=""> </div> <button type="submit">Submit</button> </form> </body> </html>
run.py
from flask import Flask,request,render_template,make_response,session,redirect,url_for app = Flask(__name__) app.secret_key = '11' @app.route('/') def index(): return render_template('index.html') @app.route('/login', methods=['GET','POST']) def login(): #Validate form data if request.method == 'POST': username = request.form['username'] password = request.form['password'] if username == 'admin' and password == 'a123': session['username'] = username #Write user name to Session session['log_in'] = True #Write login ID to Session return redirect(url_for('index')) return render_template('login.html') #Render form page @app.route('/logout') def logout(): session.clear() #Clear Session return redirect(url_for('login')) if __name__ == '__main__': app.run(debug=True, port=8000)
Run 127.0 in the browser 0.1. 8000, when not logged in, figure 1 is displayed
After logging in, figure 3 is displayed
Template inheritance
Template inheritance is similar to class inheritance in Python. Jinja2 allows you to define a base template (parent template)
Put the navigation bar and footer on the web page in the base template.
Each sub template that inherits the base template will automatically include these parts when rendered.
The advantage of using this approach is to avoid code reuse in multiple templates
In Jinja2, the keyword extends is used to inherit the child template from the parent template
Navigation bar:_ nav.html
<style> footer { position: absolute; bottom: 0; width: 100%; height: 60px; line-height: 60px; background-color: #f5f5f5; } .text-muted { color: #6c757d!important; text-align: center; } </style> <footer> <div class="text-muted"> Demacia Limited Copyright ©2007-2020, demaxiya.com, All Rights Reserved </div> </footer>
Footer:_ footer.html
<style> footer { position: absolute; bottom: 0; width: 100%; height: 60px; line-height: 60px; background-color: #f5f5f5; } .text-muted { color: #6c757d!important; text-align: center; } </style> <footer> <div class="text-muted"> Demacia Limited Copyright ©2007-2020, demaxiya.com, All Rights Reserved </div> </footer>
'use include to import'_ nav.html 'navigation bar and'_ footer.html 'bottom information bar
Parent template: base The HTML code is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="/static/css/bootstrap.css"> <script src="/static/js/jquery.js"></script> <script src="/static/js/bootstrap.js"></script> </head> <body> {% include '_nav.html' %} {% block content %} {% endblock %} {% include '_footer.html' %} </body> </html>
Home page index html
{% extends 'base.html' %} {% block content %} <main role="main"> <div class="jumbotron"> <div class="container"> <h1 class="display-3">Welcome to the home page of demacia!</h1> <p>Demacia is a powerful kingdom with supremacy of jurisprudence. It has long been famous for its outstanding military achievements. Since ancient times, demasians have advocated justice, glory and responsibility, and are almost fanatically proud of their own traditions and heritage. However, despite these noble principles, in the past few hundred years, the headstrong demacia has become increasingly isolated and synonymous with isolationism. Now, however, there are variables in the kingdom. Based on the forbidden stone, a white rock that can suppress magic energy, demassians were originally a refuge for people who sought to avoid magic after the rune war. Kingship radiates from the center to the outside, guarding remote towns, farmland, forests and mineral rich mountains. However, since the sudden death of King Gavin III, the major families have not yet approved of his only successor, Prince Gavin. In the eyes of the Kingdom, outside the heavily guarded border, there have been many dissidents, and many of the original vassals began to seek shelter from elsewhere in the troubled times. Some people privately believe that the golden age of demacia is gone. Unless the subjects can work together to adapt to the changes of the times - many people believe that they do not have such ability, the decline of the kingdom is inevitable. No amount of forbidden stones can prevent the destruction of demacia from the inside out </p> <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more »</a></p> </div> </div> </main> {% endblock %}
books.html
{% extends 'base.html' %} {% block content %} <main role="main"> <div class="jumbotron"> <div class="container"> <h1 class="display-3">Welcome to Ionia!</h1> <p>Surrounded by dangerous waters, many allied provinces formed Ionia on a huge archipelago known as the "birthplace". The pursuit of the balance of all things has been the cultural tone here for a long time, so the boundary between the material and spiritual fields is also here, especially in the wild forests and mountains. Although the magic of this land may be changeable, and the creatures that inhabit it may be dangerous and magical, the residents of Ionia have lived a rich life for the past few hundred years. Monasteries practicing martial arts, militia groups in various provinces, and even the land itself of Ionia are enough to protect local residents. But that all ended twelve years ago, because that year, Knox sent troops to attack the "birth land". The endless Imperial Army raged in Ionia. After years of hard struggle, the Ionians defeated the enemy at a huge price. Today's Ionia is in a fragile peace. Different responses to the war split the land - some groups, such as Shuo Ji's martial monks and balanced sects, want to return to isolated peace and pastoral traditions. Other more radical factions, such as the navoli brotherhood and shadow stream, advocate militarizing the magic of this land and establishing a unified country strong enough to retaliate against Knox. The fate of Ionia is hanging in a delicate balance. Few people are willing to turn it to either side, but everyone can feel the land under their feet moving</p> <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more »</a></p> </div> </div> </main> {% endblock %}
contact.html
{% extends 'base.html' %} {% block content %} <main role="main"> <!-- Main jumbotron for a primary marketing message or call to action --> <div class="jumbotron"> <div class="container"> <h1 class="display-3">contact us!</h1> <p> Business cooperation and external project cooperation (media public relations cooperation, content cooperation, brand cooperation and course group purchase business):<br> E-mail: demaxiya@.com <br> Tel: 0431-84978981 <br> </p> <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more »</a></p> </div> </div> <!-- /container --> </main> {% endblock %}
Browser access http://127.0.0.1:8000/ As follows:
Browser access http://127.0.0.1:8000/books As follows:
Browser access http://127.0.0.1:8000/contact As follows: