From: Ben Darnell Date: Mon, 30 May 2011 21:07:10 +0000 (-0700) Subject: Make template.Loader and DictLoader share a common base class X-Git-Tag: v2.0.0~39 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=3acda21a2e405e3cad7fce989f6a225a65052601;p=thirdparty%2Ftornado.git Make template.Loader and DictLoader share a common base class --- diff --git a/tornado/template.py b/tornado/template.py index d3b386126..06c10ce30 100644 --- a/tornado/template.py +++ b/tornado/template.py @@ -163,13 +163,7 @@ class Template(object): return ancestors -class Loader(object): - """A template loader that loads from a single root directory. - - You must use a template loader to use template constructs like - {% extends %} and {% include %}. Loader caches all templates after - they are loaded the first time. - """ +class BaseLoader(object): def __init__(self, root_directory): self.root = os.path.abspath(root_directory) self.templates = {} @@ -191,27 +185,35 @@ class Loader(object): def load(self, name, parent_path=None): name = self.resolve_path(name, parent_path=parent_path) if name not in self.templates: - path = os.path.join(self.root, name) - f = open(path, "r") - self.templates[name] = Template(f.read(), name=name, loader=self) - f.close() + self.templates[name] = self._create_template(name) return self.templates[name] + def _create_template(self, name): + raise NotImplementedError() + +class Loader(BaseLoader): + """A template loader that loads from a single root directory. + + You must use a template loader to use template constructs like + {% extends %} and {% include %}. Loader caches all templates after + they are loaded the first time. + """ + def _create_template(self, name): + path = os.path.join(self.root, name) + f = open(path, "r") + template = Template(f.read(), name=name, loader=self) + f.close() + return template + -class DictLoader(object): +class DictLoader(BaseLoader): """A template loader that loads from a dictionary.""" def __init__(self, dict): + super(DictLoader, self).__init__("") self.dict = dict - self.templates = {} - def reset(self): - self.templates = {} - - def load(self, name, parent_path=None): - if name not in self.templates: - self.templates[name] = Template(self.dict[name], name=name, - loader=self) - return self.templates[name] + def _create_template(self, name): + return Template(self.dict[name], name=name, loader=self) class _Node(object): diff --git a/tornado/test/template_test.py b/tornado/test/template_test.py index 120c73ba0..893711acf 100644 --- a/tornado/test/template_test.py +++ b/tornado/test/template_test.py @@ -40,3 +40,12 @@ class TemplateTest(LogTrapTestCase): }) self.assertEqual(loader.load("page.html").generate(), b("page title\npage body\n")) + + def test_relative_load(self): + loader = DictLoader({ + "a/1.html": "{% include '2.html' %}", + "a/2.html": "{% include '../b/3.html' %}", + "b/3.html": "ok", + }) + self.assertEqual(loader.load("a/1.html").generate(), + b("ok"))