From: Alek Storm Date: Sat, 20 Aug 2011 15:20:16 +0000 (+0000) Subject: Add 'namespace' parameter to template.BaseLoader constructor X-Git-Tag: v2.1.0~39^2~1^2 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=0373c7a3e644617b6a088b63a6d13d13a209cf9a;p=thirdparty%2Ftornado.git Add 'namespace' parameter to template.BaseLoader constructor Specifies custom entries in the global namespace of loaded templates. --- diff --git a/tornado/template.py b/tornado/template.py index cece87e53..29c61c421 100644 --- a/tornado/template.py +++ b/tornado/template.py @@ -117,6 +117,7 @@ class Template(object): self.autoescape = loader.autoescape else: self.autoescape = _DEFAULT_AUTOESCAPE + self.namespace = loader.namespace if loader else {} reader = _TemplateReader(name, escape.native_str(template_string)) self.file = _File(_parse(reader, self)) self.code = self._generate_python(loader, compress_whitespace) @@ -142,6 +143,7 @@ class Template(object): "_utf8": escape.utf8, # for internal use "_string_types": (unicode, bytes_type), } + namespace.update(self.namespace) namespace.update(kwargs) exec self.compiled in namespace execute = namespace["_execute"] @@ -183,7 +185,7 @@ class Template(object): class BaseLoader(object): """Base class for template loaders.""" - def __init__(self, autoescape=_DEFAULT_AUTOESCAPE): + def __init__(self, autoescape=_DEFAULT_AUTOESCAPE, namespace=None): """Creates a template loader. root_directory may be the empty string if this loader does not @@ -193,6 +195,7 @@ class BaseLoader(object): in the template namespace, such as "xhtml_escape". """ self.autoescape = autoescape + self.namespace = namespace or {} self.templates = {} def reset(self): @@ -224,7 +227,6 @@ class Loader(BaseLoader): super(Loader, self).__init__(**kwargs) self.root = os.path.abspath(root_directory) - def resolve_path(self, name, parent_path=None): if parent_path and not parent_path.startswith("<") and \ not parent_path.startswith("/") and \ diff --git a/tornado/test/template_test.py b/tornado/test/template_test.py index e04c2544a..a903f61ea 100644 --- a/tornado/test/template_test.py +++ b/tornado/test/template_test.py @@ -74,7 +74,11 @@ class TemplateTest(LogTrapTestCase): else: template = Template(utf8(u'{{ u"\u00e9" }}')) self.assertEqual(template.generate(), utf8(u"\u00e9")) - + + def test_custom_namespace(self): + loader = DictLoader({"test.html": "{{ inc(5) }}"}, namespace={"inc": lambda x: x+1}) + self.assertEqual(loader.load("test.html").generate(), b("6")) + class AutoEscapeTest(LogTrapTestCase): def setUp(self):