Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Refactor template namespace from render_string to its own method.

This method may be overridden as an alternative to overriding render_string
and adding to kwargs, or may be used directly to render templates
without going through render_string (as when templates are constructed
directly; see tornadoweb#564)
  • Loading branch information...
commit 58671703d35937d98898ff76571513b6c9678451 1 parent 30bc233
Ben Darnell bdarnell authored
Showing with 19 additions and 6 deletions.
  1. +17 −5 tornado/web.py
  2. +2 −1  website/sphinx/web.rst
22 tornado/web.py
View
@@ -106,7 +106,7 @@ class RequestHandler(object):
def __init__(self, application, request, **kwargs):
super(RequestHandler, self).__init__()
-
+
self.application = application
self.request = request
self._headers_written = False
@@ -602,7 +602,20 @@ def render_string(self, template_name, **kwargs):
else:
loader = RequestHandler._template_loaders[template_path]
t = loader.load(template_name)
- args = dict(
+ namespace = self.get_template_namespace()
+ namespace.update(kwargs)
+ return t.generate(**namespace)
+
+ def get_template_namespace(self):
+ """Returns a dictionary to be used as the default template namespace.
+
+ May be overridden by subclasses to add or modify values.
+
+ The results of this method will be combined with additional
+ defaults in the `tornado.template` module and keyword arguments
+ to `render` or `render_string`.
+ """
+ namespace = dict(
handler=self,
request=self.request,
current_user=self.current_user,
@@ -612,9 +625,8 @@ def render_string(self, template_name, **kwargs):
xsrf_form_html=self.xsrf_form_html,
reverse_url=self.reverse_url
)
- args.update(self.ui)
- args.update(kwargs)
- return t.generate(**args)
+ namespace.update(self.ui)
+ return namespace
def create_template_loader(self, template_path):
settings = self.application.settings
3  website/sphinx/web.rst
View
@@ -9,7 +9,7 @@
Entry points
^^^^^^^^^^^^
-
+
.. automethod:: RequestHandler.initialize
.. automethod:: RequestHandler.prepare
.. automethod:: RequestHandler.on_finish
@@ -47,6 +47,7 @@
.. automethod:: RequestHandler.finish
.. automethod:: RequestHandler.render
.. automethod:: RequestHandler.render_string
+ .. automethod:: RequestHandler.get_template_namespace
.. automethod:: RequestHandler.redirect
.. automethod:: RequestHandler.send_error
.. automethod:: RequestHandler.write_error
Please sign in to comment.
Something went wrong with that request. Please try again.