Flask template

1. Functions that can be called in every template

@app.template_global()
def ad(a1,a2):
    """
    Functions that can be called in each template
    :stop a1:
    :param a2:
    :return:
    """
    return a1+a2

2. In order to prevent xss attacks, verification is added, and the page is displayed in the form of a string. We don't want him to display it like this, so there are two ways

Method 1: Import Markup in the backend

from flask import Flask,render_template,redirect,jsonify,make_response,Markup
def gen_input(value):
    return Markup("<input value='%s'/>" %value)

Method two:

Add |safe to the front end

   <h1>{{k5(99)|safe}}</h1>

3. Template inheritance

Like django's, extends

4. Examples

s1.py

from flask import Flask,render_template,redirect,jsonify,make_response,Markup

app = Flask(__name__)

@app.template_global()
def ad(a1,a2):
    """
    Functions that can be called in each template
    :stop a1:
    :param a2:
    :return:
    """
    return a1+a2


def gen_input(value):
    # return Markup("<input value='%s'/>" %value)
    return "<input value='%s'/>" %value
@app.route('/index',methods=['GET','POST'])
def index():
    context = {
        'k1':123,
        'k2':[11,22,33],
        'k3':{'name':'oldboy','age':73},
        'k4':lambda x:x+1,
        'k5':gen_input,

    }
    return render_template('index.html',**context)


@app.route('/x2',methods=['GET','POST'])
def order():
    context = {
        'k1':123,
        'k2':[11,22,33],

    }
    return render_template('order.html',**context)

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

templates

  layout.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>header</div>
<div>
    {% block content%}
    {% endblock%}
</div>
<div>bottom</div>
</body>
</html>

index.html

{% extends 'layout.html'%}
{% block content%}
   <h1>{{k1}}</h1>
   <h1>{{k2.0}} {{k2[1]}}</h1>
   <h1>{{k3.name}} {{k3['age']}} {{k3.get('name',888)}} </h1>
   <h1>{{k4(66)}}  </h1>
   <!--<h1>{{k5(99)}}  </h1>-->

   <h1>{{ad(1,2)}}  </h1>

{% endblock %}

order.html

{% extends 'layout.html'%}
{% block content%}
 <h1>{{ad(1,2)}}  </h1>
{% endblock %}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325094726&siteId=291194637