How to use the introductory tutorial for templates in the Python flask framework

Source: Internet
Author: User
Tags html page inheritance tmp folder

How do I get started with templates in the flask framework of Python?

Overview

If you've already read the previous chapter, you should have completed the full preparation and created a simple Web application with the following file structure:

Microblog

|-flask folder

|-< files for some virtual environments >

|-app folder

| |-static folder

| |-templates folder

| |-__init__.py file

| |-views.py file

|-tmp folder

|-run.py file

The above gives you an introductory tutorial on using templates in the Python flask framework, which I hope will help you.

We will continue to develop our applications at the end of the previous chapter in the following chapters, so make sure your environment is installed correctly and your application is working properly.

Why we need to use the template system

Let's consider how we can expand our applet next.

We want to implement a very basic function in the micro-blogging application, which shows a title of the user who is welcome to the login. For the time being, I will be able to solve the problem by ignoring the current application in which there is no user status.

The easiest way to display a nice, elegant title is to change the way we provide the view to display some HTML code, rather than:

?

1 2 3 4, 5 6 7 8 9 10 11 12 13 14 15 From the app Import app @app. Route ('/') @app. Route ('/index ') def index (): User = {' nickname ': ' Miguel '} # Fake user return ' '

Now, in your browser to refresh the look, is it cool?

Because our applet also supports user functions, I use a user placeholder, which is usually affectionately called fake or test data. It allows us to focus on the parts of the program that are in need of resolution.

Well done, face the reality, I hope you will feel the above mixed with HTML code applet is quite disgusting. Think of it as a very painful thing to do if you create a complex HTML page with some dynamic content and want to change some page content in a Web site made up of such programs.

Template system Saves the world

If you keep your business logic and performance separate, your site structure will be better organized. Don't believe it, if you're using Python to complete the business code, you can even ask a web designer to help you with the rest. Template system is to help you achieve business and performance separation.

Let's finish the first template (fileapp/templates/index.html):

?

1 2 3 4 5 6 7 8

As you can see, we've just written an ordinary HTML page, and the only difference to HTML is that there are some dynamic content placeholders with {{...}}}.

Now let's look at how the template is handled in the View function (fileapp/views.py):

?

1 2 3 4 5 6 7 8 9 10 From flask import Render_template the From app Import app @app. Route ('/') @app. Route ('/index ') def index (): User = {' Nickna Me ': ' Miguel '} # Fake user return render_template ("index.html", title = ' Home ', user = user)

The key to testing this program is to see how the template system works. You can compare the HTML page in the browser after the source code and template file source code differences.

In the above program, we import a new function called Render_template from the Flask framework and use this function to render the template. and gives this function the template filename and some variables as arguments. It replaces the variable placeholders in the template with the imported variables and returns the rendered template.

Let's get a little deeper. At the bottom of the flask, the render_template function actually invokes a component of the flask: the JINJA2 template processing engine. is Jinjia2 the corresponding {{...}} code block in the template with the imported variables.

Process Control in a template

JINJA2 template system also supports process control statements, let's try to add an If Process Control statement (fileapp/templates/index.html) to the template:

?

1 2 3 4 5 6 7 8 9 10 11-12

Now our template file is a little smart. If we forget to define the page title variable title in the View function, it will use its own title instead. Try to cancel the title variable in the render_template in the view function and see how the IF Process statement works.

Use loops in templates

Maybe users want to show their friends ' recent articles on his home page, a bit like everyone else, or a friend of Sina Weibo, and then we'll see how to do that.

First, create users and articles (fileapp/views.py):

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14-15 16 def index (): User = {' nickname ': ' Miguel '} # Fake user posts = [# Fake array of posts {' author ': {' nickname ': ' John ' }, ' body ': ' Beautiful Day in portland! '}, {' author ': {' nickname ': ' Susan '}, ' body ': ' The Avengers movie is so cool! ' ] Return render_template ("index.html", title = ' Home ', user = user, posts = posts)

Using an array to store the user's article, each array element is a dictionary, as shown in the code above, this Dict key is author and body, used to store the author and article content of the article. When we decide to use a database to store this information, the key of the dictionary can be insinuate as a field in the table, in order to give you a demonstration of the use of the template, not using database-related techniques, simply using dictionaries and arrays of simulated users and his friends recently published articles.

Our template file now has a new problem. We have just created a content data containing the user's article, which may contain any number of articles. How to make the template automatically render content based on the number of this array.

To solve this problem, a new Process Control statement is needed: For loop. Let's add the for loop to the template file (fileapp/templates/index.html)

?

1 2 3 4, 5 6 7 8 9 10 11 12 13 14 15

Quite simply, you can also add more content to the array to see the effect.

Template inheritance

Next, we need to add a navigation menu to the microblogging (microblog) that contains similar links, such as modifying personal data, exiting logins, and so on.

It is also possible to directly add this navigation bar directly to the index.html template file, but when we have a lot of template files that contain this navigation bar, we get bogged down in the awkward situation of having to edit and return to multiple files in order to modify the navigation bar somewhere. When you have more and more files that contain this navigation bar, you will have the heart to die.

We can use the Jinja2 template inheritance feature, which allows us to combine some of the common content in the template to create an underlying template, and then let other templates inherit the underlying template.

Let's first define a basic template that contains the navigation bar and the first written process Control statement about the page title (title). (fileapp/templates/base.html):

?

1 2 3 4 5 6 7 8 9 10 11 12 13-14

In this template, we use the Block control statement to define where the content of the inherited template is to be displayed. Note: The name set in this block statement must be unique.

Next, let's revise the index.html template so that it inherits from the underlying template base.html (fileapp/templates/index.html) that you just added:

?

1 2 3 4 5 6 7 {% extends ' base.html '%} {% block content%}

The basic template base.html helped us with the page structure and the public content, so this index.html template became the loser. The extends statement associates two templates. When the index.html template is rendered, Jinja2 discovers the extends statement, it automatically introduces the base.html base template and matches the block statement named content in two templates. JINJA2 knows how to merge two templates together. When we create a new template later, we also use this method that inherits from the underlying template.

Here's a guide to how to use the Templates tutorial in the Python flask framework, and hopefully it will help.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.