tornada-模板
2024-08-30 12:48:34
tornado模板
1.配置模板路径 (project/config.py)
# coding=utf-8
import os
BASE_DIRS = os.path.dirname(__file__)
# 参数
options = {
“post” : 8000,
}
# 配置
settings = {
"static_path" : os.path.join(BASE_DIRS,"static"),
"template_path":os.path.join(BASE_DIRS,"templates"),
"debug":True,
}
2.配置URL路由(project/application.py)
# coding = utf-8
import tornado.web
from views import views
import config class Application(tornado.web.Application):
def __init__(self):
app = [
(r"/home",views.HomeHandler),
]
super(Application, self).__init__(app, **config.settings)
3.渲染并返回给客户端(project/views/views.py)
# coding = utf-8
# 视图 from tornado.web import RequestHandler class HomeHandler(RequestHandler):
def get(self, *args, **kwargs):
temp = 100
per = {"name" : "hello", "age":18}
self.render("home.html", num = temp, per = per)
# 方法2
self.render("home.html", num = temp, **per)
4.变量与表达式(project/templates/home.html)
- 语法
- {{ var }}
- {{ expression }}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>主页</title>
</head>
<body>
<h1>这里是home页面</h1>
<h1>num: {{ num }}</h1>
<h1>per["name"]</h1>
<h1>{{name}}</h1>
</body>
</html>
5.流程控制
- if
- {% if 表达式 %} ......{% elif 表达式 %} ......{% else %}..... {%end%}
- for
- {% for item in items %} ...... {%end%}
- while
6.函数
- static_url
- <link rel="stylesheet" href="{{ static_url('css/home.css') }}">
- 优点1: 修改目录不需要修改URL
- 优点2:创建了一个基于文件内容的hash值,并将其添加到URL末尾(当一个查询参数),这个hash值总能保证加载的是最新的文件,而不是以前的缓存版本。无论是开发阶段还是上线阶段都是很有必要的。
- 自定义函数
# 把函数当参数传递
class FuncHandler(RequestHandler):
def get(self, *args, **kwargs):
def mySum(n1,n2):
return n1+n2
self.render(‘home.html’,mysum = mySum) # 在 home.html 中使用
<h1>{{ mysum(100,99) }}</h1>
7.转义
- 作用
- tornado默认开启了自动转义功能,能防止网址受到恶意攻击
我们可以通过raw语句来输出不被转义的原始格式,如:
{% raw text %}
注意: 只能关闭一行;在Firefox浏览器中会直接弹出alert窗口,而在Chrome浏览器中,需要set_header("X-XSS-Protection", 0)
若要关闭自动转义:
一种方法是在Application构造函数中传递autoescape=None
另一种方法是在每页模板中修改自动转义行为,添加如下语句:
{% autoescape None %}
escape()
关闭自动转义后,可以使用escape()函数来对特定变量进行转义,如:
{{ escape(text) }}
8.块
我们可以使用块来复用模板,块语法如下:
{% block block_name %} {% end %}
而子模板index.html使用extends来使用父模板base.html,如下:
{% extends "base.html" %}
9.静态文件
- static_path
- "static_path":os.path.join(BASE_DIRS, "static")
- StaticFileHandler (静态文件)
- 注意:放在所有的路由下面(在application.py中)
(r"/(.*)$", tornado.web.StaticFileHandler,{“path”:os.path.join(config.BASE_DIRS,"static/html"),
"default_filename":"index.html"})
最新文章
- Linux系统中Xampp+Bugfree安装
- FormatJS – 让你的 Web 应用程序国际化
- IOS-Appium 自动化测试——环境配置及模拟器、真机跑测试
- eclipse中python文本字体大小设置
- PHP文件头部(header)解释
- NHibernate框架魅力美
- 移动端tab滑动和上下拉刷新加载
- SpringBoot中跨域问题
- centos7.4 linux 指令
- Matlab中hold on与hold off的用法
- SpringCloud-分布式配置中心(基于SpringBoot2.X)
- selenium+Java使用内容记录(全)
- GIFDecoder源码分析
- UVa 11729 突击战
- 源码中transient的用途
- sqlite时间戳转时间语句(时间转时间戳)实例
- Concurrent Request:Inactive phase,No Manager status
- Ubuntu16.04下 protobuf3.4.0 的安装与卸载
- DML、DDL、DCL是什么?
- MyBatis如何返回自增的ID