A, templates,

The key to an easy-to-maintain application is to write clean, well-structured code. The examples you’ve seen so far are too simple to illustrate this, but the two completely separate functions of the Flask view function are fused together, which creates a problem.

Don’t tell me you don’t know how to write simple applications in Flask again! As shown in the example. This is sufficient for simple requests. But in many cases, requests change the state of the application, and that change happens in view functions.

Take the example of a user registering a new user on a website. The user enters an email and password into a form, and then clicks the submit button. The server receives a request containing user data, and Flask dispatches the request to the view function that handles the registration request. This view function needs to access the database, add a new user, and then generate a response back to the browser indicating success or failure. These two processes are called business logic and presentation logic respectively.

Mixing business logic with presentation logic can lead to code that is difficult to understand and maintain. If you are building HTML code for a large table, the data in the table is concatenated with data read from the database and the necessary HTML strings, migrating presentation logic to templates can improve the maintainability of your application.

A template is a file that contains the response text and contains the dynamic portion of the placeholder variable representation, whose exact value is known only in the context of the request. The process of replacing variables with real values and returning the resulting response string is called rendering. Flask uses a powerful template named Jinja2 to render templates.

1.1 Jinja2 Template engine

In its simplest form, a Jinja2 template is a file that responds to text.

Create the HTML file in the Templates folder

Example 1-1 templates/index. HTML

<h1>Hello world</h1>
Copy the code

Example 1-2 templates/user. HTML

<h1>Hello,{{name}}</h1>
Copy the code

1.1.1 Render Templates

Flask, by default, looks for templates in the Templates subdirectory of the application directory.

Example 1-3 Hello. py render template

from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def index() :
    return render_template('index.html')


@app.route('/user/<name>')
def user(name) :
    return render_template('user.html', name=name)
Copy the code

Flask provides a **render_template()** function to integrate the Jinja2 template engine into the application. The first parameter is the filename of the template, followed by key-value pairs (keyword arguments) that represent the specific values of the template variables. In this code, a variable named name is received in the second template.

Example 1-4 hello. Py

from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def index() :
    # class
    class Person(object) :
        name = u'p17bdw'
        age = 18

    person1 = Person()
    context = {
        'username': 'c17bdw'.'gender': U 'male'.'age': 17.'person': person1,
        'websites': {
            'baidu': 'www.baidu.com'.'google': 'www.google.com'}}return render_template('index.html', **context)
Copy the code

1.1.2 variable

A variable is represented in a template using the {{name}} structure, which is a special placeholder that tells the template that the value was taken from the data used to render the template.

In examples 1-3, by wrapping the context, you can access the data in the context via variables in the template.

Example 1-5 index. HTML

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>This is the text that appears in HTML</h1>

<p>Username: {{username}}</p>
<p>Gender: {{gender}}</p>
<p>Age: {{age}}</p>

<hr >
<p>Name: {{person. Name}}</p>
<p>Age: {{person. Age}}</p>

<hr >
<p>Baidu: {{websites [' baidu]}}</p>
<p>Google: {{websites [' Google ']}}</p>

</body>
</html>
Copy the code

As you can see from the above code examples, Jinja2 recognizes all variable types, even complex ones such as lists, dictionaries, and objects.

1.1.3 Control structure

Jinja2 provides a variety of control structures that can be used to change the rendering process of a template.

Example 1-6 if_statement. Py

Enter http://127.0.0.1:5000/1/ to log in; otherwise, you are not logged in
from flask import Flask, render_template


app = Flask(__name__)


@app.route('/<is_login>/')
def index(is_login) :
    if is_login == '1':
        user = {
            'username': U 'Book-learning'.'age': 18
        }
        return render_template('index.html', user=user)
    else:
        return render_template('index.html')
Copy the code

Example 1-7 index. HTML

<! DOCTYPEhtml>
<html lang="zh">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title></title>
</head>
<body>
	<! When user is present and age is greater than 15, the page rendering effect is -->
	{% if user and user['age'] > 15 %}
		<a href="#">{{user['username']}}</a>
		<a href="#">The cancellation</a>
	
	{% else %}
		<a href="#">The login</a>
		<a href="#">registered</a>
	{% endif %}
</body>
</html>
Copy the code

The running difference in the example code above is the difference between logged in and not logged in.

1.1.4 Loop Structure

Example 1-8 for_statement. Py

from flask import Flask, render_template

app = Flask(__name__)
# for traversing the dictionary
@app.route('/')
def index() :
    books = [
        {
            'name': Journey to the West.'author': 'Wu Cheng 'en'.'price': 109
        },
        {
            'name': A Dream of Red Mansions.'author': 'Cao Xueqin'.'price': 200
        },
        {
            'name': Romance of The Three Kingdoms.'author': 'Luo Guanzhong'.'price': 120
        },
        {
            'name': 'Water Margin'.'author': 'Nai am'.'price': 130}]return render_template('index.html', books=books)
Copy the code

In this section, notice the last line of code. The first books is to be handed in and accessed by the HTML code, and the second books is the books defined in the code

Example 1-9 index. HTML

<! DOCTYPEhtml>
<html lang="zh">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title></title>
</head>
<body>
	<table border="1">
		<thead>
			<th>Title:</th>
			<th>The author</th>
			<th>The price</th>
		</thead>
	</table>
	<tbody>
		{% for book in books %}
			<tr>
				<td>{{book.name}}</td>
				<td>{{book.author}}</td>
				<td>{{book.price}}</td>
			</tr>
		{% endfor %}
	</tbody>
</body>
</html>
Copy the code

1.1.5 filter

1. Introduction and Usage

  • Introduction: Filters can process variables, the original variables after processing and then displayed. The objects are variables.
  • Grammar:

{{ avatar|default(‘xxx’) }}

2, default filter: if the current variable does not exist, this time can specify the default value.

3, length filter: find list, string, dictionary, tuple length.

4. Introduction of common filters

The filter function
abs(value) Return an absolute value
first(value) Returns the sequence of the first value, example: names | first
last(value) Return to the last value sequence, example: names | last
length(value) Returns a sequence of length, example: names | length
join(value, d=’u’) Concatenate a sequence into a string using the d argument

Flask recognizes all of them.

Take a look at the following example:

index.html

<! DOCTYPEhtml>
<html lang="zh">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>The filter</title>
</head>
<body>
	
	<p>Comments: ({{comments | length}})</p>
	{% for comment in comments %}
		<li>
			<a href="#">{{comment.user}}</a>
			<p>{{comment.content}}</p>
		</li>
</body>
</html>		
Copy the code

filter_dmeo.py

from flask import Flask,render_template

app = Flask(__name__)


@app.route('/comments')
def index() :
    comments = [
        {
            'user': 'Joe'.'content': 'the up refueling'
        },
        {
            'user': 'bill'.'content': 'undo'}]return render_template('index.html', comments=comments)

Copy the code

1.1.6 Inheritance and Blocks

To avoid code reuse, you can use template inheritance, which is similar to inheritance in Python code.

1. The role and syntax of inheritance

  • What it does: You can put common code into the parent template, so that each template does not have to write the same code.
  • Syntax: {% extend base.html %}

2, the implementation of block

  • What it does: You can make a subtemplate implement its own requirements. The parent template needs to be defined in advance
  • Note: The code for the child template must be in a block block.

base.html

<! DOCTYPEhtml>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
	<title>{% block title %}{% endblock %}</title>

	<style type="text/css">
		.nav {
			background: #3a3a3a;
			height: 65px;

		}
		ul {
			overflow: hidden;

		}

		ul li {
			float: left;
			list-style: none;
			padding: 0 10px;
			line-height: 65px;

		}

		ul li a {
			color: #fff
		}
	</style>
	{% block head %}{% endblock %}
</head>
<body>

	<div class="nav">
		<ul>
			<li><a href="#">Home page</a></li>
			<li><a href="/login">Release q&a</a></li>
		</ul>
	</div>
	{% block main %}{% endblock %}


	
</body>
</html>
Copy the code

index.html

{% extends base.html %}

{% block head %}
<style type="text/css">
	
</style>

<link rel="stylesheet" type="text/css" href="">
<script type="text/javascript"></script>{% endblock %} {% endblock %} {% endblock main %}Copy the code

login.html

{% extends "base.html" %} {% block title %} {% endblock %} {% block main %}Copy the code

app.py

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index() :
	return render_template('index.html')

@app.route('/login/')
def login() :
	return render_template('login.html')

Copy the code

This is an example of inheritance, putting common code into base.html (the parent class), using blocks and endblocks in the file, and then substituting them in the subclass.

2.1 Bootstrap integration using flask-Bootstrap

Bootstrap is an open source framework developed by Twitter that provides user components to create a clean Web page. And compatible with modern desktop and mobile web browsers.

We are now going to use the Flask-Bootstrap extension, which can be installed using PIP

pip install flask-bootstrap
Copy the code

Next, take a look at how bootstrap is used.

user.html

{% extends "bootstrap/base.html" %}

{% block title %}flask{% endblock %}

{% block navbar %}
<div class="navbar navbar-inverse" role="navigation">
	
	<div class="container">
		 <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="/">flasky</a>
    </div>
	</div>

	 <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active"><a href="/">Home</a></li>
      </ul>
    </div><! -- /.navbar-collapse -->
</div>
{% endblock %}

{% block content %}
<div class="container">
	<div class="page-header">
		<h1>Hello,{{name}}</h1>
	</div>
</div>
{% endblock %}
Copy the code

hello.py

from flask import Flask, render_template
from flask_bootstrap import Bootstrap


app = Flask(__name__)
bootstrap = Bootstrap(app)

@app.route('/user/<name>/')
def user(name) :
    return render_template('user.html', name=name)

@app.route('/') :
def index() :
	return '<h1>Hello world</h1>'
Copy the code

2.2 the link

Any application with multiple routes needs links that can connect to different pages. Take the navigation bar.

It is not difficult to write urls for simple routes directly in templates, but it is difficult to build urls in templates for dynamic routes with variable parts.

To avoid these problems, Flask provides the url_for() helper function, which causes the information saved in the URL map to generate urls.

The simplest use of the url_for() function takes the view function name as an argument and returns the corresponding URL.

When url_for() generates a dynamic URL, the dynamic part is passed in as a keyword argument.

Usage:

Replace \ in the template engine with url_for(‘index’).

2.3 Static Files

Web applications consist not only of Python source code and templates, but also of many static files, such as CSS, images, and JS files.

Flask, with the default Settings, looks for static files in a subdirectory named static in the application root directory, where subfiles can be added if desired

Usage:

url_for('static', filename='css/style.css')
Copy the code

The last

Wise men know that the world is large, but they know little.

Willing to tolerate different people and opinions, have the ability to learn and change themselves, constantly input progressive information, to update their ideas.

Point a [look], let us together in the network era, do a sober smart, not by big data control, but unaware of the stupid.

I am shujun, a person who concentrates on learning. The more you know, the more you don’t know, and I’ll see you next time!