zoukankan      html  css  js  c++  java
  • 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 = '<h1>测试xss</h1>'
        return render_template('index.html',info=USER,classes=classes,schools=schools,age=age,safe_test=safe_test)
    
    @app.route('/login')
    def login():
        return Markup('<h1>我最帅</h1>')  # 
    
    if __name__ == '__main__':
        app.run()
    

    index.html

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <!--字符串渲染-->
    <p>
        classes: {{ classes }}
    </p>
    
    <!--列表取值-->
    {{schools.0}}
    {{schools[1]}}
    {{schools[:-1]}}
    <!--列表循环-->
    <ul>
        {% for school in schools %}
        <li>{{ school }}</li>
        {% endfor%}
    </ul>
    
    <!--字典循环-->
    {% for key,val in info.items() %}  
        {{ val.name}}
        {{ val['name']}}
        {{ val.get('name')}}
    {% endfor %}
    
    <!--逻辑判断-->
    {% if age > 10 %}
        <h1>{{age}}</h1>
    {% endif %}
        
    无safe时,不解析标签 {{safe_test}}
    <br>
    有safe时,解析标签{{safe_test|safe}}
    </body>
    </html>
    

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

    from flask import Flask,render_template,Markup,jsonify,make_response
    app = Flask(__name__)
    
    def func1(arg):
        return Markup("<input type='text' value='%s' />" %(arg,))
    @app.route('/')
    def index():
        return render_template('index.html',ff = func1)  # 传了函数过去
    
    if __name__ == '__main__':
        app.run()
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    	<!--执行函数-->
        {{ff('六五')}}  
    	{{ff('六五')|safe}}
    </body>
    </html>
    

    注意:

    1.Markup等价django的mark_safe

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

  • 相关阅读:
    使用MyBatis时接收值和返回值选择Map类型或者实体类型
    如何在开发时部署和运行前后端分离的JavaWeb项目
    6月22日项目CodeReview问题及总结
    【转载】CSRF攻击及其应对之道
    【转载】MySQL事务以及SELECT ... FOR UPDATE的使用
    win10打开SQLServer, SQL Server 配置管理器
    iframe标签和frame标签异同
    8款让你耳目一新的软件开发工具
    快速开发平台的比较
    CSDN:Java Web 开发平台 WebBuilder 专访
  • 原文地址:https://www.cnblogs.com/863652104kai/p/11604923.html
Copyright © 2011-2022 走看看