From 6f0a3612c240940e079e06f1c16c65a6c1b54a7d Mon Sep 17 00:00:00 2001 From: Chris Jerdonek Date: Tue, 16 Oct 2012 23:51:24 -0700 Subject: Address issue #122: add Renderer.render_name(). This commit adds a Renderer.render_name() method that lets one render a template given its name. --- pystache/loader.py | 2 ++ pystache/renderer.py | 11 +++++++++++ pystache/tests/common.py | 8 +++++--- pystache/tests/test_renderer.py | 7 +++++++ 4 files changed, 25 insertions(+), 3 deletions(-) (limited to 'pystache') diff --git a/pystache/loader.py b/pystache/loader.py index 5855392..d4a7e53 100644 --- a/pystache/loader.py +++ b/pystache/loader.py @@ -33,6 +33,8 @@ class Loader(object): """ Loads the template associated to a name or user-defined object. + All load_*() methods return the template as a unicode string. + """ def __init__(self, file_encoding=None, extension=None, to_unicode=None, diff --git a/pystache/renderer.py b/pystache/renderer.py index 20e4d48..49be4a0 100644 --- a/pystache/renderer.py +++ b/pystache/renderer.py @@ -341,6 +341,17 @@ class Renderer(object): return self._render_string(template, *context, **kwargs) + def render_name(self, template_name, *context, **kwargs): + """ + Render the template with the given name using the given context. + + See the render() docstring for more information. + + """ + loader = self._make_loader() + template = loader.load_name(template_name) + return self._render_string(template, *context, **kwargs) + def render_path(self, template_path, *context, **kwargs): """ Render the template at the given path using the given context. diff --git a/pystache/tests/common.py b/pystache/tests/common.py index 307a2be..99be4c8 100644 --- a/pystache/tests/common.py +++ b/pystache/tests/common.py @@ -43,7 +43,10 @@ def html_escape(u): return u.replace("'", ''') -def get_data_path(file_name): +def get_data_path(file_name=None): + """Return the path to a file in the test data directory.""" + if file_name is None: + file_name = "" return os.path.join(DATA_DIR, file_name) @@ -139,8 +142,7 @@ class AssertStringMixin: format = "%s" # Show both friendly and literal versions. - details = """String mismatch: %%s\ - + details = """String mismatch: %%s Expected: \"""%s\""" Actual: \"""%s\""" diff --git a/pystache/tests/test_renderer.py b/pystache/tests/test_renderer.py index 69cc64d..df518f9 100644 --- a/pystache/tests/test_renderer.py +++ b/pystache/tests/test_renderer.py @@ -368,6 +368,13 @@ class RendererTests(unittest.TestCase, AssertStringMixin): # TypeError: decoding Unicode is not supported self.assertEqual(resolve_partial("partial"), "foo") + def test_render_name(self): + """Test the render_name() method.""" + data_dir = get_data_path() + renderer = Renderer(search_dirs=data_dir) + actual = renderer.render_name("say_hello", to='foo') + self.assertString(actual, u"Hello, foo") + def test_render_path(self): """ Test the render_path() method. -- cgit v1.2.1