Getting started with using templates in the Python Flask framework, pythonflask

Source: Internet
Author: User
Tags tmp folder

Getting started with using templates in the Python Flask framework, pythonflask

Overview

If you have read the previous chapter, you should have fully prepared and created a simple Web application with the following file structure:
 
Microblog
|-Flask folder
|-<Files in some virtual environments>
|-App folder
|-Static folder
|-Templates folder
|-_ Init _. py file
|-Views. py file
|-Tmp folder
|-Run. py file

Do you want to run this program? Run the run. py file and open the http: // localhost: 5000 address in your browser.

We will continue to develop our applications at the end of the previous chapter. Therefore, make sure that your environment has been correctly installed and your applications can run properly.
 

Why do we need to use the template system?

Let's take a look at how we can expand our small programs.

We need to implement a very basic function in the Weibo application, and display a title on the homepage that welcomes the logged-on users. ignore the absence of users in the current application. I will solve this problem later.

To display a beautiful and generous title, the simplest way is to change the way we provide the view to display some HTML code :\
 

from app import app @app.route('/')@app.route('/index')def index():  user = { 'nickname': 'Miguel' } # fake user  return '''

Now, refresh it in your browser to see if it is great?
 

Because our applet also supports user functions, we use a user placeholder object, which is often affectionately called false data or test data. It allows us to focus on what is urgently needed in the program.

I hope you will think that the above small program mixed with html code is quite disgusting. Think about it. If you want to use dynamic content to generate a complex HTML page and want to change some page content in a website composed of such programs, this will be a very bad thing.

Template system saves the world

If you keep the separation of business logic and performance, your website structure will be better organized. Don't believe it. If you use python to complete the business code, you can even ask a website designer to help you complete the rest. The template system separates your business from your performance.

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

As you can see, we just wrote a common HTML page. The only difference with HTML is that it contains some dynamic content placeholders consisting.


Now let's take a look at how the view function processes this template (fileapp/views. py ):
 

from flask import render_templatefrom app import app @app.route('/')@app.route('/index')def index():  user = { 'nickname': 'Miguel' } # fake user  return render_template("index.html",    title = 'Home',    user = user)

The focus of testing this program is to see how the template system works. You can compare the differences between the rendered html page source code in the browser and the template file source code.

In the above program, we imported a new function named render_template from the Flask framework and used this function to render the template. The template file name and some variables are assigned as parameters to this function. It replaces the imported variables with the placeholder variables in the template and returns the rendered template.

Let's take a deeper look. At the bottom layer of Flask, The render_template function actually calls a component of Flask: Jinja2 template processing engine. Jinjia2 replaced the {...} code block in the template with the imported variable.

Process control in the template

The Jinja2 template system also supports flow control statements. Let's try to add an if flow control statement (fileapp/templates/index.html) in the template ):
 

Now our template file is a bit intelligent. If we forget to define the title variable title in the view function, it will use its own title instead. Cancel the title variable in render_template in the view function to see how the if flow statement works.

Use loops in templates

Maybe the user wants to display the articles recently written by his friends on his homepage, a little like the news of friends like everyone or Sina Weibo. Next we will look at how to complete this function.

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

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 was so cool!'    }  ]  return render_template("index.html",    title = 'Home',    user = user,    posts = posts)

Store Users' Articles Using arrays. Each array element is a dictionary. As shown in the code above, the key of this dict is author and body, which are used to store the author and content of the articles. When we decide to use a database to store this information, the key of this dictionary can be invisible as a field in the Table. Here, we do not use database-related technologies to demonstrate the use of the template, the dictionary and array are used to simulate the recent articles published by users and their friends.
 

Our template file now has a new problem. We have just created a data entry that contains user articles. This array may contain any number of articles. How can we make the template automatically render content based on the number of the array.

To solve this problem, a new flow control statement is required: for Loop. Let's add the for loop to the template file (fileapp/templates/index.html)
 

You can also add more content to the array to see the effect.
 
Template inheritance

Next, we need to add a navigation menu for this Weibo blog, which contains similar links such as modifying personal data and logging out.

Adding this navigation bar directly to the index.html template file is also feasible, but when many template files contain this navigation bar, it will be stuck in the embarrassment of having to edit multiple files in order to modify the navigation bar somewhere. When there are more and more files containing this navigation bar, you may want to die.


We can use the Jinja2 template inheritance function, which allows us to combine some common content in the template to create a basic template, and then let other templates inherit this basic template.

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

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


Next, let's modify the index.html template to inherit from the newly added basic template base.html (fileapp/templates/index.html ):

 

{% extends "base.html" %}{% block content %}

The basic template base.html helps us deal with the Page Structure and public content, so this index.html template is just like this. The extends statement associates the two templates. When Jinja2 renders the index.html template and finds the extends statement, it automatically introduces the base.html Basic Template and matches the block statement named content in the two templates. Jinja2 knows how to merge the two templates. We will also use this method to inherit from the basic template when creating a new template later.

Conclusion

If you want to save time and do not bother coding, you can download the sample code of this chapter from the following address:

: Microblog-0.2.zip

Related Article

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.