Tornado-Lesson04-模版、模版转义、静态文件的引用

一、模版

  1.模版的概念

     在tornado中,模版就是一个html文件。可以动态的传入参数,python表达式,以改变模版的内容

  2.模版的符号

    1){{ ... }}

      中间可以写入python表达式或者一个变量

    2){% ... %}   {% end %} 

      用来写模版命令,如if,for,while等,注意命令结束时要添加{% end %}

    3){# ... #}

      模版中的注释语句,让模版命令不执行

 

  3.模版的转义和去转义

    tornado默认自动转义,当模版传入一个字符串时,字符串中的html语句不会被解析,而是当作一个字符串直接打印在上面。

    如果要解析需要去转义。

    1)局部去转义——{% raw ... %}

       {% raw ... %} 在变量外添加,tornado在渲染的时候不会去转义变量

 

    2)模块去转义——{% autoescape None %}

      在模版中添加{% autoescape None %},当前模版不再转义

      如果模块中部分代码需要转义,可以使用{{ escape(...) }}

 

    3)全局去转义——autoescape=None

       在tornado的Application配置中添加autoescape = None,整个项目不再转义

       如果模块中部分代码需要转义,可以使用{{ escape(...) }}

二、静态文件的引用

    在Application中配置static_path = 'static'  添加此配置后,tornado就可以自己找到静态文件

    两种引入方式:

      1.<img src="static/images/img_bg_0.jpg" width="580" height="363">

      2.<img src="{{static_url('images/img_bg_3.jpg')}}" width="580" height="363">

    从tornado主要模块web.py中Application类的__init()__方法中可以看到对静态文件的处理

class Application(ReversibleRouter):
    if self.settings.get("static_path"):
        path = self.settings["static_path"]
        handlers = list(handlers or [])
        static_url_prefix = settings.get("static_url_prefix",
                                         "/static/")
        static_handler_class = settings.get("static_handler_class",
                                            StaticFileHandler)
        static_handler_args = settings.get("static_handler_args", {})
        static_handler_args['path'] = path
        for pattern in [re.escape(static_url_prefix) + r"(.*)",
                        r"/(favicon.ico)", r"/(robots.txt)"]:
            handlers.insert(0, (pattern, static_handler_class,
                                static_handler_args))

    第三行path = self.settings["static_path"]可以看出来需要的配置static_path

    其他参数:   

      static_url_prefix:静态文件的URL前缀,可以对静态文件的访问路径进行设置,默认为 "/static/"

      static_handler_class:处理静态文件的类,可以自定义处理静态文件的动作,默认的为 tornado.web.StaticFileHandler

      static_handler_args:处理静态文件的参数,如果设置了,应该有一个字典被传入到static_handler_class类的 initialize 方法中

以下代码来实现以上的内容  test.py

class LoginHandler(tornado.web.RequestHandler):
    def get(self, *args, **kwargs):
        self.write('templates')
        self.render('login.html')

    def post(self, *args, **kwargs):
        user = self.get_argument('name', 'no')
        a = 0;
        s1 = '<a href="http://www.qq.com" target="_blank">腾讯</a>'
        urllist = [
            ('https://www.baidu.com', '百度'),
            ('http://www.qq.com', '腾讯')
        ]
        self.render('temp.html', username = user, time = time, fun = function_01, urllist = urllist, s1 = s1)

application = tornado.web.Application(
    handlers = [
    (r"/login", LoginHandler )],
    autoescape = None,            #全局去转义
    debug=True,
    static_path = 'static',
    template_path = 'templates'
)

  login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tornado</title>
</head>
<body>
Welcome!

<form method="post" action="/login">
    <p>用户名<br><input type="text" name="name"></p>
    <p>密码<br><input type="password" name="password"></p>
    <input type="submit">
</form>


</body>
</html>

  temp.html

<!DOCTYPE html>
{# autoescape None #}  <!--模版去转义-->
<html lang="en"> <head> <meta charset="UTF-8"> <title>Temp</title> </head> <body> {{ username }}, How are you!  <!--传入参数-->
<br> {{ time.time() }} <br> {{ fun() }}    <!--传入函数-->
<br>  
<!--各种命令用法-->
{% if username == 'wjl' %} VIP{{ username }}, Welcome! <img src="static/images/img_bg_0.jpg" width="580" height="363"> <img src="{{static_url('images/img_bg_3.jpg')}}" width="580" height="363"> {% else %} {{ username }}, Welcome! {% end %} <br> {% for i in urllist %} <a href="{{i[0]}}" target="_blank">{{i[1]}}</a> {% end %} <br> {% set a = 0 %} {% while a < 5 %} {{a}} {% set a += 1 %}
{% end %}
<br>

<!--注释用法-->
{# time.time() #} <br> {{ s1 }}<br> {% raw s1 %}<br>   <!--局部去转义-->  {{ escape(s1) }}  <!--局部转义-->
</body> </html>

  运行结果:

  

原文地址:https://www.cnblogs.com/bear905695019/p/8486590.html