2.Flask jinjia2 template

2.Flask jinjia2 template

1.1. Template parameter transfer

(1) Main program

from flask import Flask,render_template

app = Flask(__name__)

@app.route('/')
def hello_world():

    context = {
        'username':'derek',
        'age': 18,
        'gf':{
            'name':'xxx',
            'height': 160
        }
    }
    return render_template('index.html',**context) #Add double underscores to get the key and value directly

if __name__ =='__main__':

    app.run(debug=True)

(2) index.html

  <h2>Rendering data in the template</h2>
    <p>{{ username }}</p>
    <p>{{ age }}</p>
    <p>{{ gf.name }}</p>
    <p>{{ gf['height'] }}</p>

1.2. Filter

 Commonly used filters

  • abs: absolute value
  • default: If the current variable has no value, the value in the parameter will be used instead
  • escape: escape character
  • first: returns the first element of a sequence
  • format: format string
  • last: returns the last element of a sequence
  • length: returns the length of a sequence
  • join: concatenate strings
  • safe: turn off escaping
  • int: converted to int type
  • float: convert to floating point type
  • lower: convert to lowercase
  • upper: convert to thank you
  • replace: replace
  • truncate: intercept a string of length length
  • striptags: delete all html tags in the string, if there are multiple spaces, they will be replaced with one space

 Use of default filter

Main program

from flask import Flask,render_template
app = Flask(__name__)

@app.route('/')
def hello_world():

    context = {
       'position':-9,
       'signature':None #personal signature
    }
    return render_template('index.html',**context)

if __name__ =='__main__':
    app.run(debug=True)

index.html

  <h2>Filter</h2>
    <p>{{ position|abs }}</p>
    <p>Individual signature: {{ signature|default('This person is lazy and did not leave any explanation',boolean=True) }}</p>

You can also use or

 <h2>Filter</h2>
    <p>{{ position|abs }}</p>
{# <p>Individual signature: {{ signature|default('This person is lazy and did not leave any explanation',boolean=True) }}</p>#}
    <p>Individual signature: {{ signature or'This person is lazy and did not leave any explanation' }}</p>

1.3. Custom filter

      The filter is essentially a function. If the filter is called in the template, the value of this variable will be passed to the function of the filter as the first parameter.

Then the return value of the function will be used as the return value of this filter. Need to use a decorator: @app.template_filter('args')

Example: custom time processing filter

 Main program

from flask import Flask,render_template
from datetime import datetime
app = Flask(__name__)

@app.route('/')
def hello_world():
    context = {
        'create_time': datetime(2018,5,25,17,52,10)
    }
    return render_template('index.html',**context)

@app.template_filter('handle_time') #The name in the brackets is the name of the filter
def handle_time(time):
    '''
    1. If the time interval is less than 1 minute, it will display "just now"
    2. If it is within 1 hour, "xx minutes" will be displayed
    3. If within 24h, display "xx hours ago"
    4. If it is more than 24 hours and 30 days, it will display "xx days ago"
    5. More than one month, show the specific time
    :param time:
    :return:
    '''
    if isinstance(time,datetime):
        now = datetime.now()
        timestamp = (now-time).total_seconds() #The current time is the number of seconds from the creation time
        if timestamp <60: within #60s
            return "just now"
        elif timestamp >= 60 and timestamp <60*60:
            minutes = timestamp/60
            return "%s minutes ago"%int(minutes)
        elif timestamp >= 60*60 and timestamp <60*60*24:
            hours = timestamp/(60*60)
            return'%s hours ago'%int(hours)
        elif timestamp >= 60*60*24 and timestamp <60*60*24*30:
            days = timestamp/(60*60*24)
            return'%s days ago'%int(days)
        else:
            return time.strftime('%Y/%m/%d %H:%M')
    else:
        return time

if __name__ =='__main__':
    app.run(debug=True)

index.html

 <h2>Custom time filter</h2>
    {{ create_time|handle_time }}

1.4. The use of if and for

The for contains the following variables, which can be used to get the current traversal status

  • loop.index
  • loop.index0
  • loop.first
  • loop.last
  • loop.length

Simple usage of if and for

from flask import Flask,render_template

app = Flask(__name__)
app.config.update({
    'DEBUG':True,
    'TEMPLATES_AUTO_RELOAD':True
})

@app.route('/')
def hello_world():
    context = {
        'age': 20,
        'users':['tom','jack','alice'],
        'person':{
            'name':'derek',
            'age': 18
        }
    }
    return render_template('index.html',**context)

if __name__ =='__main__':
    app.run(debug=True)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    {% if age >= 18 %}
        welcome
    {% else %}
        No permission
    {% endif %}

    <ul>
    {% for user in users %}
        <li>{{ user }}</li>
    {% endfor %}
    </ul>

    <table>
        <thead>
            <tr>
                <th>Username</th>
                <th>Age</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                {% for key,value in person.items() %}
                    <td>{{ value }}</td>
                {% endfor %}
            </tr>
        </tbody>
    </table>

</body>
</html>

1.5. Use and import of macros

The template macro is similar to the function in python. You can pass parameters but not return values. You can put some frequently used code snippets into the macro, and then put some

Unfixed values ​​are extracted as a variable.

(1) Simple use case

{# Define a macro, input is the name of the macro, with three parameters in it, you can specify the default parameter value, you can also call the parameter#}
    {% macro input(name="",value="",type="text") %}
        <input name="{{ name }}" value="{{ value }}" type="{{ type }}">
    {% endmacro %}

    <form>
        <p>User name: {{ input('username') }}</p>
        <p>Password: {{ input('password',type="password" )}}</p>
        <p> {{ input(value="Submit",type="submit" )}}</p>

    </form>

(2) Two ways to import macros

New macros.html

 {% macro input(name="",value="",type="text") %}
        <input name="{{ name }}" value="{{ value }}" type="{{ type }}">
    {% endmacro %}

Import and use macros in index.html

{#The first#}
{# with context can pass the variables from the backend to the current template to the defined macro#}
{% import "macros.html" as macro with context %}    
{#二种#}
{% from "macros.html" import input as input_field %}


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{# The first#}
    <form>
        <p>User name: {{ macro.input('username') }}</p>
        <p>Password: {{ macro.input('password',type="password" )}}</p>
        <p> {{ macro.input(value="submit",type="submit" )}}</p>
    </form>

{# 2.Type#}
     <form>
        <p>User name: {{ input_field('username') }}</p>
        <p>Password: {{ input_field('password',type="password" )}}</p>
        <p> {{ input_field(value="submit",type="submit" )}}</p>
    </form>

</body>
</html>

1.6.set, with custom variables in the template

 (1) set

You can use set to define variables in the template. Once you define this variable, you can use it in the code behind, index.html

{% set usernmae='derek' %}

    <p>User name: {{ usernmae }}</p>

(2) with

The variable defined by the with statement can only be used in the with statement code block (endwith). If it exceeds the code block, it can no longer be used. The set statement does not have an end and is used globally.

{% with age=18 %}
        <p>Age:{{ age }}</p>
    {% endwith %}

1.7. Use of blueprints

The directory is as follows:

(1) news.py

from flask import Blueprint


news_bp = Blueprint('new',__name__,url_prefix='/news')

@news_bp.route('/list/')
def news_list():
    return'news list'

(2) user.py

from flask import Blueprint

# 1. Define a blueprint,'user': the name of the blueprint, url_prefix='/user': add a prefix to the url, be careful not to add a'/' after it
user_bp = Blueprint('user',__name__,url_prefix='/user')

@user_bp.route('/profile/')
def profile():
    return'personal center'

(3) bluepoint_demo.py

from flask import Flask,url_for
# 2. Import
from blueprints.user import user_bp
from blueprints.news import news_bp

app = Flask(__name__)
# 3. Registration Blueprint
app.register_blueprint(user_bp)
app.register_blueprint(news_bp)

@app.route('/')
def hello_world():
    return'Hello World!'

with app.test_request_context():
    print(url_for('new.news_list')) #/news/list/Add the name of the blueprint when reversing the url through url_for
    print(url_for('user.profile')) #/user/profile/

if __name__ =='__main__':
    app.run(debug=True)
Reference: https://cloud.tencent.com/developer/article/1390513 2. Flask jinjia2 template-cloud + community-Tencent Cloud