Getting started with templates in Python's flask framework

Source: Internet
Author: User
Tags tmp folder
Overview

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

Microblog
|-flask folder
|- <一些虚拟环境的文件>
|-app folder
| |-static folder
| |-templates folder
| |-__init__.py file
| |-views.py file
|-tmp folder
|-run.py file

Pro, want to run this program? Then run the run.py file and open the http://localhost:5000 address in your browser.

We continue to develop our applications in the sections that follow in the previous chapter, so make sure your environment is properly installed and your app works.

Why we need to use a templating system

Let's think about how we can expand our applet next.

We want to implement a very basic function in the microblog application, and display the title of a welcome signed-in user on the first page. Ignoring the current application without the user's condition, I will solve this problem later.

The simplest way to display an aesthetically pleasing title is to change the way we provide the view to display some HTML code, which is less like this: \

From app Import App @app. Route ('/') @app. Route ('/index ') def index ():  user = {' nickname ': ' Miguel '} # fake user  re Turn ""   Home Page    

Hello, ' + user[' nickname ' + '

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

Because our small program also supports the user function, so we use a user placeholder object, usually it is affectionately referred to as false data or test data. It allows us to focus on the parts of the program that need to be addressed urgently.

When you're done, I hope you'll find this little program mixed with HTML code quite disgusting. Think about it, if you use a complex HTML page generated by some dynamic content and want to change some page content in a Web site made up of such programs, it will be a very painful thing to do.

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've done your business code with Python, you can even ask a web designer to help you with the rest. The template system is to help you achieve separation of business and performance.

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

   {{title}}-Microblog     

Hello, {{user.nickname}}!

As you can see, we just wrote a normal HTML page, the only thing that is different from HTML is that it has some dynamic content placeholders that are made up of {{...}}.


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

From flask import render_templatefrom 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 templating system works. You can compare the browser in the rendered HTML page source code and template file the difference between the source code.

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 the function a template file name and some variables as parameters. It replaces the imported variable with the variable placeholder in the template and returns the rendered template.

Let's get a little deeper. At the bottom of the Flask, the Render_template function actually calls a component of Flask: the JINJA2 template processing engine. Jinjia2 replaced the corresponding {{...}} code block in the template with the imported variable.

Process Control in a template

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

   {% if title%}  {{title}}-Microblog  {% Else%}  Welcome to microblog  {% ENDIF%}     

Hello, {{user.nickname}}!

Now our template file is a little bit smarter. If we forget to define the page title variable title in the View function, it will be replaced with its own title. Cancel the title variable in the render_template in the view function and see how the If flow statement works.

Using Loops in templates

Maybe the user wants to show a friend's recent writing on his page, a bit like everyone, or a friend of Sina Weibo, and then we'll see how to do it.

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

def index ():  user = {' nickname ': ' Miguel '} # Fake user  posts = [# Fake array of posts    {      ' author ': {' n Ickname ': ' 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)

Storing the user's article with an array, 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 the content of the article. When we decided to use the database to store this information, this dictionary key can be insinuate as a field of the table, here in order to demonstrate the use of the template, not using database-related technology, simply using dictionaries and arrays to simulate the user and his friends recently published articles.

Our template file now has a new problem. We have just created a content data that contains user articles, 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 required: for loop. Let's add a for loop to the template file (fileapp/templates/index.html)

   {% if title%}  {{title}}-Microblog  {% Else%}  Microblog  {% ENDIF%}    

Hi, {{user.nickname}}!

{% for post in posts%}

{{Post.body}}

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 this Weibo (microblog), which contains similar links for modifying profiles, exiting logins, and so on.

It is also possible to 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 are stuck in the awkward position of having to go back and forth in multiple files in order to modify the navigation bar somewhere. When the file containing the navigation bar is getting more and more, the heart that you want to die will be there.


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

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

   {% if title%}  {{title}}-Microblog  {% Else%}  Microblog  {% ENDIF%}    Microblog:home    

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


Let's change the index.html template so that it inherits from the base template base.html (fileapp/templates/index.html) you just added:


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

Hi, {{user.nickname}}!

{% for post in posts%}

{{Post.body}}

{% ENDFOR%} {% Endblock%}

The basic template base.html helped us get the page structure and public content, so this index.html template is a bad example. The extends statement associates two templates with each other. JINJA2 when rendering the index.html template, the extends statement is automatically introduced base.html the base template, and a block statement named content in two templates is matched. JINJA2 knows how to merge two templates together. We will also use this method of inheriting from the underlying template when we create a new template later.

Conclusion

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

Download 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.