• tornado下模板引擎的使用


    模板引擎

      Tornado中的模板语言和django中类似,模板引擎将模板文件载入内存,然后将数据嵌入其中,最终获取到一个完整的字符串,再将字符串返回给请求者。

      Tornado =的模板支持“控制语句”和“表达语句”,控制语句是使用 {% 和 %} 包起来的 例如 {% if len(items) > 2 %}。表达语句是使用 {{ 和 }} 包起来的,例如 {{ items[0] }}

      控制语句和对应的 Python 语句的格式基本完全相同。我们支持 ifforwhile 和 try,这些语句逻辑结束的位置需要用 {% end %} 做标记。还通过 extends 和 block 语句实现了模板继承。这些在 template 模块 的代码文档中有着详细的描述。

      tornado模 板语言,无论for或者if,结尾都是end,不像django的endfor、endif;另外,tornado模板语言,取数据时跟python一模一样,如下面的取字典里的数据,可以直接dict['key'],也可以dict.get('key','default');不像django里的item.1。

      注:在使用模板前需要在setting中设置模板路径:"template_path" : "tpl"

    1.基本使用

    import tornado.ioloop
    import tornado.web
      
    class MainHandler(tornado.web.RequestHandler):
        def get(self):
            self.render("index.html", list_info = [11,22,33],title='Mytitle')
      
    application = tornado.web.Application([
        (r"/index", MainHandler),
    ])
      
    if __name__ == "__main__":
        application.listen(8888)
        tornado.ioloop.IOLoop.instance().start()
    app.py
    <html>
       <head>
          <title>{{ title }}</title>
       </head>
       <body>
         <ul>
           {% for item in list_info %}
             <li>{{item)}}</li>
           {% end %}
         </ul>
       </body>
     </html>
    index.html

      表达式可以是任意的Python表达式, 包括函数调用. 模板代码会在包含以下对象 和函数的命名空间中执行 (注意这个列表适用于使用 RequestHandler.render 和 render_string 渲染模板的情况. 如果你直接在 RequestHandler 之外使用 tornado.template 模块, 下面这些很多都不存 在)

    在模板中默认提供了一些函数、字段、类以供模板使用:
    
    escape: tornado.escape.xhtml_escape 的別名
    xhtml_escape: tornado.escape.xhtml_escape 的別名
    url_escape: tornado.escape.url_escape 的別名
    json_encode: tornado.escape.json_encode 的別名
    squeeze: tornado.escape.squeeze 的別名
    linkify: tornado.escape.linkify 的別名
    datetime: Python 的 datetime 模组
    handler: 当前的 RequestHandler 对象
    request: handler.request 的別名
    current_user: handler.current_user 的別名
    locale: handler.locale 的別名
    _: handler.locale.translate 的別名
    static_url: for handler.static_url 的別名
    xsrf_form_html: handler.xsrf_form_html 的別名
    其他方法

    2.继承

    <html>
    <body>
        <header>
            {% block header %}{% end %}
        </header>
        <content>
            {% block body %}{% end %}
        </content>
        <footer>
            {% block footer %}{% end %}
        </footer>
    </body>
    </html>
    layout.html

    当我们扩展父模板layout.html时,可以在子模板index.html中引用这些块。

    {% extends "layout.html" %}
    
    {% block header %}
        <h1>{{ header_text }}</h1>
    {% end %}
    
    {% block body %}
        <p>Hello from the child template!</p>
    {% end %}
    
    {% block footer %}
        <p>{{ footer_text }}</p>
    {% end %}
    index.html

    3、导入(include)

    <div>
        <ul>
            <li>1024</li>
            <li>42区</li>
        </ul>
    </div>
    header.html
    <!DOCTYPE html>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>title</title>
        <link href="{{static_url("css/common.css")}}" rel="stylesheet" />
    </head>
    <body>
    
        <div class="pg-header">
            {% include 'header.html' %}
        </div>
        
        <script src="{{static_url("js/jquery-1.8.2.min.js")}}"></script>
        
    </body>
    </html>
    index.html

    4、自定义UIMethod以UIModule

    a. 定义

    # uimethods.py
     
    def tab(self):
        return 'UIMethod'
    uimethods.py
    from tornado.web import UIModule
    from tornado import escape
    
    class custom(UIModule):
    
        def render(self, *args, **kwargs):
            return escape.xhtml_escape('<h1>hello world</h1>')
           
    uimodules.py

    b. 注册

    import tornado.ioloop
    import tornado.web
    from tornado.escape import linkify
    import uimodules as md
    import uimethods as mt
    
    class MainHandler(tornado.web.RequestHandler):
        def get(self):
            self.render('index.html')
    
    settings = {
        'template_path': 'template',
        'static_path': 'static',
        'static_url_prefix': '/static/',
        'ui_methods': mt,
        'ui_modules': md,
    }
    
    application = tornado.web.Application([
        (r"/index", MainHandler),
    ], **settings)
    
    
    if __name__ == "__main__":
        application.listen(8009)
        tornado.ioloop.IOLoop.instance().start()
    View Code

    c. 使用

    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <title></title>
        <link href="{{static_url("commons.css")}}" rel="stylesheet" />
    </head>
    <body>
        <h1>hello</h1>
        {% module custom(123) %}
        {{ tab() }}
    </body>
    View Code

    5、模板的自动转义问题

      Tornado默认会自动转义模板中的内容,把标签转换为相应的HTML实体。这样可以防止后端为数据库的网站被恶意脚本攻击。比如,你的网站中有一个评论部分,用户可以在这里添加任何他们想说的文字进行讨论。虽然一些HTML标签在标记和样式冲突时不构成重大威胁(如评论中没有闭<h1>标签),但<script>标签会允许攻击者加载其他的JavaScript文件,打开通向跨站脚本攻击、XSS或漏洞之门。

      所有模板输出默认都会使用 tornado.escape.xhtml_escape 函数转义. 这个行为可以通过传递 autoescape=None 给 Application 或者 tornado.template.Loader 构造器来全局改变, 对于一个模板文件可以使 用 {% autoescape None %} 指令, 对于一个单一表达式可以使用 {% raw ...%} 来代替 {{ ... }}. 此外, 在每个地方一个可选的 转义函数名可以被用来代替 None.

      方法一:是在Application构造函数中传递autoescape=None,另一种方法是在每页的基础上修改自动转义行为,如下所示:

    {% autoescape None %}
    {{ mailLink }}

    这些autoescape块不需要结束标签,并且可以设置xhtml_escape来开启自动转义(默认行为),或None来关闭。

      然而,在理想的情况下,你希望保持自动转义开启以便继续防护你的网站。因此,你可以使用{% raw %}指令来输出不转义的内容。

    {% raw mailLink %}
  • 相关阅读:
    iOS开发UI篇—Quartz2D使用(图片剪切)
    LeanCloud存取数据
    Pod搜不到类库解决办法
    第三方的工具以及插件
    苹果开发账号申请注意事项
    苹果账号网址汇总
    代码规范
    流媒体
    iOS面试题
    安装 Alcatraz
  • 原文地址:https://www.cnblogs.com/freely/p/6759627.html
Copyright © 2020-2023  润新知