From 6a85be4577fa1d3177d0da5e8abe20b06a6c90c6 Mon Sep 17 00:00:00 2001 From: Ben Darnell Date: Mon, 30 May 2011 19:03:54 -0700 Subject: [PATCH] Add autoescape application setting and convert chatdemo to use it. --- demos/chat/chatdemo.py | 1 + demos/chat/templates/index.html | 4 ++-- demos/chat/templates/message.html | 3 +-- tornado/web.py | 15 +++++++++++++-- 4 files changed, 17 insertions(+), 6 deletions(-) diff --git a/demos/chat/chatdemo.py b/demos/chat/chatdemo.py index b9ad716b..48f8a908 100755 --- a/demos/chat/chatdemo.py +++ b/demos/chat/chatdemo.py @@ -43,6 +43,7 @@ class Application(tornado.web.Application): template_path=os.path.join(os.path.dirname(__file__), "templates"), static_path=os.path.join(os.path.dirname(__file__), "static"), xsrf_cookies=True, + autoescape="xhtml_escape", ) tornado.web.Application.__init__(self, handlers, **settings) diff --git a/demos/chat/templates/index.html b/demos/chat/templates/index.html index de051d85..c38190b1 100644 --- a/demos/chat/templates/index.html +++ b/demos/chat/templates/index.html @@ -7,7 +7,7 @@
@@ -24,7 +24,7 @@ - {{ xsrf_form_html() }} + {% raw xsrf_form_html() %} diff --git a/demos/chat/templates/message.html b/demos/chat/templates/message.html index 20edbe7a..64d2f67f 100644 --- a/demos/chat/templates/message.html +++ b/demos/chat/templates/message.html @@ -1,2 +1 @@ -{% import tornado.escape %} -
{{ escape(message["from"]) }}: {{ tornado.escape.linkify(message["body"]) }}
+
{{ message["from"] }}: {% raw linkify(message["body"]) %}
diff --git a/tornado/web.py b/tornado/web.py index ecc686fe..adcfae3c 100644 --- a/tornado/web.py +++ b/tornado/web.py @@ -543,8 +543,7 @@ class RequestHandler(object): if not getattr(RequestHandler, "_templates", None): RequestHandler._templates = {} if template_path not in RequestHandler._templates: - loader = self.application.settings.get("template_loader") or\ - template.Loader(template_path) + loader = self.create_template_loader(template_path) RequestHandler._templates[template_path] = loader t = RequestHandler._templates[template_path].load(template_name) args = dict( @@ -561,6 +560,18 @@ class RequestHandler(object): args.update(kwargs) return t.generate(**args) + def create_template_loader(self, template_path): + settings = self.application.settings + if "template_loader" in settings: + return settings["template_loader"] + kwargs = {} + if "autoescape" in settings: + # autoescape=None means "no escaping", so we have to be sure + # to only pass this kwarg if the user asked for it. + kwargs["autoescape"] = settings["autoescape"] + return template.Loader(template_path, **kwargs) + + def flush(self, include_footers=False): """Flushes the current output buffer to the network.""" if self.application._wsgi: