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 https://github.com/facebook/tornado/issues/564)
This commit is contained in:
Ben Darnell 2012-08-26 17:43:38 -07:00
parent 30bc2332fb
commit 58671703d3
2 changed files with 19 additions and 6 deletions

View File

@ -602,7 +602,20 @@ class RequestHandler(object):
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 @@ class RequestHandler(object):
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

View File

@ -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