Flask快速入门(5) — 模板渲染

Flask快速入门(5) — 模板渲染

视图函数

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

@app.route('/',endpoint='index')
def index():
    age = 18
    classes = '班级'
    schools = ['s1','s2','s3']
    USER = {
        1: {'name': 'Nick', 'age': 18, 'hobby': ['study', 'swimming']},
        2: {'name': 'Bob', 'age': 19, 'hobby': ['basketball', 'game']},
        3: {'name': 'Link', 'age': 17, 'hobby': ['sing', 'dance']},
        4: {'name': 'Sean', 'age': 20, 'hobby': ['game', 'walking']},
    }
    safe_test = '

测试xss

' return render_template('index.html',info=USER,classes=classes,schools=schools,age=age,safe_test=safe_test) @app.route('/login') def login(): return Markup('

我最帅

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

index.html




    
    Title



classes: {{ classes }}

{{schools.0}} {{schools[1]}} {{schools[:-1]}}
    {% for school in schools %}
  • {{ school }}
  • {% endfor%}
{% for key,val in info.items() %} {{ val.name}} {{ val['name']}} {{ val.get('name')}} {% endfor %} {% if age > 10 %}

{{age}}

{% endif %} 无safe时,不解析标签 {{safe_test}}
有safe时,解析标签{{safe_test|safe}}

与django不同的是,在flask中模板渲染可以用[],()之类的,执行函数,传参数。

from flask import Flask,render_template,Markup,jsonify,make_response
app = Flask(__name__)

def func1(arg):
    return Markup("" %(arg,))
@app.route('/')
def index():
    return render_template('index.html',ff = func1)  # 传了函数过去

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



    
    Title


    
    {{ff('六五')}}  
    {{ff('六五')|safe}}

注意:

1.Markup等价django的mark_safe

2.用于模板的extends,include与django中的一模一样

转载于:https://www.cnblogs.com/863652104kai/p/11604923.html

你可能感兴趣的:(Flask快速入门(5) — 模板渲染)