Flask template (1) and flask Template

Source: Internet
Author: User

Flask template (1) and flask Template

The use of templates helps to separate the business logic from the presentation logic, making it easier to maintain. A template is a Web page Code that has been created. Some dynamic data must be replaced with specific values in the request context.

The Jinja2 template engine is used in flask and stored in the templates folder.

templates/index.html

Use {name} placeholder

templates/user.html

 

Template Rendering

Template rendering replaces the placeholder variable in the template with real values.

from flask import Flask,render_template@app.route('/')def index():    return render_template('index.html',name=name)

Variables can be obtained from lists, dictionaries, and objects.

<p>A value from a dict:{{ mydict['key'] }}</p><p>A value from a list:{{ mylist[3] }}</p><p>A value from a list with a variable index:{{ mylist[intvar] }}</p><p>A value from a object's method :{{ myobj.mymethod() }}</p>

Use the filter to modify the variable:

{{ name|capitalize }}

Common filters:

Filter Name Description
Safe Do not escape during rendering
Capitalize Upper-case letters and lower-case letters
Lower Lowercase
Upper Uppercase
Title Uppercase letters of each word
Trim Remove leading and trailing Spaces
Striptags Delete all html tags in the value

 

 

 

 

 

 

 

 

Control Structure

 

{% if user %}    Hello,{{ user }}{% else %}    Hello,Stranger!{% endif %}

 

<ul>    {% for comment in comments %}        <li>{{ comment }}</li>    {% endfor %}</ul>

 

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.