]> git.ipfire.org Git - thirdparty/tornado.git/commitdiff
Add 'namespace' parameter to template.BaseLoader constructor 340/head
authorAlek Storm <alek.storm@gmail.com>
Sat, 20 Aug 2011 15:20:16 +0000 (15:20 +0000)
committerAlek Storm <alek.storm@gmail.com>
Sat, 20 Aug 2011 15:20:16 +0000 (15:20 +0000)
Specifies custom entries in the global namespace of loaded templates.

tornado/template.py
tornado/test/template_test.py

index cece87e53ad64ca231ff8042b13e4fd51a91e694..29c61c42115e93a244706b4a177e9f06ae15a495 100644 (file)
@@ -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 \
index e04c2544acc477eebd839e3bfc5b02ef6d61de8b..a903f61eadc2a978e3f381ee7360e7cfe94275cc 100644 (file)
@@ -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):