zoukankan      html  css  js  c++  java
  • Flask学习笔记07之模板渲染

    flask提供了局部和全局两种方式的数据,用于模板渲染

    @app.template_global()

    @app.template_filter()

    如果函数上面有这两个装饰器之一,那么该函数就可以全局模板渲染

    from flask import Flask, render_template, Markup
    
    app = Flask(__name__)
    
    app.debug = True
    
    
    def func(arg):
        return arg + 1
    
    
    @app.template_global()
    def global_template(arg1, arg2):
        """
        @app.template_global 装饰了global_template 这个方法,
        那么, global_template就是一个全局的模板,随便哪儿都可以用、
        :param arg1:
        :param arg2:
        :return:
        """
        return arg1 + arg2
    
    @app.template_filter()
    def filter_template(arg1,arg2,arg3):
        """
        也是一个全局模板,但是使用方法与template_global不同
        :param arg1:
        :param arg2:
        :param arg3:
        :return:
        """
        return arg1+arg2+arg3
    
    
    @app.route('/user')
    def index():
        context = {'users': ['小明', '小强'],
                   'txt': '<input type = "text" /input>',
                   # Markup 表示可信任
                   'html': Markup('<input type = "text" /input>'),
                   'func': func
                   }
        return render_template("user.html", **context)
    
    
    if __name__ == '__main__':
        app.run()
    

    视图user.html代码 

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
    {{ users.0 }}
    {{ users[1] }}
    
    {#以字符串的形式展示,防止了xss攻击 #}
    {{ txt }}
    
    {#信任#}
    {{ txt| safe }}
    
    {{ html }}
    {{ func(8) }}
    {{ global_template(1,2) }}
    
    {#真是有点扯蛋#}
    {{ 1| filter_template(2,3) }}
    </body>
    </html>
    
  • 相关阅读:
    Linux
    python中元类
    POJ 1182 食物链
    POJ 1733 Parity game
    top 介绍
    周记 2014.8.31
    windows10配置python
    oracle执行update时卡死问题的解决办法
    An Easy Introduction to CUDA C and C++
    super()
  • 原文地址:https://www.cnblogs.com/z-qinfeng/p/12303963.html
Copyright © 2011-2022 走看看