Commit 4cf7281e by Chris Jerdonek

Merge 'issue_59' into development: closing issue #59 (Template -> Renderer)

parents b6018af6 a36cd00a
......@@ -20,7 +20,7 @@ import sys
# ValueError: Attempted relative import in non-package
#
from pystache.loader import Loader
from pystache.template import Template
from pystache.renderer import Renderer
USAGE = """\
......@@ -64,8 +64,10 @@ def main(sys_argv):
except IOError:
context = json.loads(context)
template = Template(template)
print(template.render(context))
renderer = Renderer()
rendered = renderer.render(template, context)
print rendered
if __name__=='__main__':
......
......@@ -5,12 +5,12 @@ This module contains the initialization logic called by __init__.py.
"""
from .template import Template
from .renderer import Renderer
from .view import View
from .loader import Loader
__all__ = ['Template', 'View', 'Loader', 'render']
__all__ = ['render', 'Loader', 'Renderer', 'View']
def render(template, context=None, **kwargs):
......@@ -18,5 +18,5 @@ def render(template, context=None, **kwargs):
Return the given template string rendered using the given context.
"""
template = Template(template)
return template.render(context, **kwargs)
renderer = Renderer()
return renderer.render(template, context, **kwargs)
......@@ -20,22 +20,20 @@ except ImportError:
pass
class Template(object):
class Renderer(object):
def __init__(self, template=None, load_template=None, output_encoding=None, escape=None,
# TODO: change load_template to load_partial.
def __init__(self, load_template=None, output_encoding=None, escape=None,
default_encoding=None, decode_errors='strict'):
"""
Construct a Template instance.
Construct an instance.
Arguments:
template: a template string that is either unicode, or of type
str and encoded using the encoding named by the default_encoding
keyword argument.
load_template: the function for loading partials. The function should
accept a single template_name parameter and return a template as
a string. Defaults to the default Loader's load_template() method.
load_template: a function for loading templates by name, for
example when loading partials. The function should accept a
single template_name parameter and return a template as a string.
Defaults to the default Loader's load_template() method.
output_encoding: the encoding to use when rendering to a string.
The argument should be the name of an encoding as a string, for
......@@ -84,7 +82,6 @@ class Template(object):
self.escape = escape
self.load_template = load_template
self.output_encoding = output_encoding
self.template = template
def _unicode_and_escape(self, s):
if not isinstance(s, unicode):
......@@ -146,9 +143,9 @@ class Template(object):
escape=self._unicode_and_escape)
return engine
def render(self, context=None, **kwargs):
def render(self, template, context=None, **kwargs):
"""
Return the template rendered using the given context.
Render the given template using the given context.
The return value is a unicode string, unless the output_encoding
attribute has been set to a non-None value, in which case the
......@@ -160,6 +157,10 @@ class Template(object):
Arguments:
template: a template string that is either unicode, or of type
str and encoded using the encoding named by the default_encoding
keyword argument.
context: a dictionary, Context, or object (e.g. a View instance).
**kwargs: additional key values to add to the context when rendering.
......@@ -169,13 +170,12 @@ class Template(object):
engine = self._make_render_engine()
context = self._make_context(context, **kwargs)
template = self.template
if not isinstance(template, unicode):
template = self.unicode(template)
result = engine.render(template, context)
rendered = engine.render(template, context)
if self.output_encoding is not None:
result = result.encode(self.output_encoding)
rendered = rendered.encode(self.output_encoding)
return result
return rendered
......@@ -10,7 +10,7 @@ from types import UnboundMethodType
from .context import Context
from .loader import Loader
from .template import Template
from .renderer import Renderer
class View(object):
......@@ -68,7 +68,7 @@ class View(object):
def _get_template_name(self):
"""
Return the name of this Template instance.
Return the name of the template to load.
If the template_name attribute is not set, then this method constructs
the template name from the class name as follows, for example:
......@@ -98,9 +98,9 @@ class View(object):
Return the view rendered using the current context.
"""
template = Template(self.get_template(), self.load_template, output_encoding=encoding,
escape=escape)
return template.render(self.context)
template = self.get_template()
renderer = Renderer(self.load_template, output_encoding=encoding, escape=escape)
return renderer.render(template, self.context)
def get(self, key, default=None):
return self.context.get(key, default)
......
......@@ -2,7 +2,7 @@
import unittest
import pystache
from pystache import template
from pystache import renderer
class PystacheTests(object):
......@@ -114,16 +114,16 @@ class PystacheWithoutMarkupsafeTests(PystacheTests, unittest.TestCase):
"""Test pystache without markupsafe enabled."""
def setUp(self):
self.original_markupsafe = template.markupsafe
template.markupsafe = None
self.original_markupsafe = renderer.markupsafe
renderer.markupsafe = None
def tearDown(self):
template.markupsafe = self.original_markupsafe
renderer.markupsafe = self.original_markupsafe
# If markupsafe is available, then run the same tests again but without
# disabling markupsafe.
_BaseClass = unittest.TestCase if template.markupsafe else object
_BaseClass = unittest.TestCase if renderer.markupsafe else object
class PystacheWithMarkupsafeTests(PystacheTests, _BaseClass):
"""Test pystache with markupsafe enabled."""
......@@ -132,5 +132,5 @@ class PystacheWithMarkupsafeTests(PystacheTests, _BaseClass):
non_strings_expected = """(123 & ['something'])(chris & 0.9)"""
def test_markupsafe_available(self):
self.assertTrue(template.markupsafe, "markupsafe isn't available. "
self.assertTrue(renderer.markupsafe, "markupsafe isn't available. "
"The with-markupsafe tests shouldn't be running.")
......@@ -9,25 +9,28 @@ import codecs
import sys
import unittest
from pystache import template
from pystache.template import Template
from pystache import renderer
from pystache.renderer import Renderer
class TemplateTestCase(unittest.TestCase):
class RendererTestCase(unittest.TestCase):
"""Test the Template class."""
"""Test the Renderer class."""
def setUp(self):
"""
Disable markupsafe.
"""
self.original_markupsafe = template.markupsafe
template.markupsafe = None
self.original_markupsafe = renderer.markupsafe
renderer.markupsafe = None
def tearDown(self):
self._restore_markupsafe()
def _renderer(self):
return Renderer()
def _was_markupsafe_imported(self):
return bool(self.original_markupsafe)
......@@ -36,7 +39,7 @@ class TemplateTestCase(unittest.TestCase):
Restore markupsafe to its original state.
"""
template.markupsafe = self.original_markupsafe
renderer.markupsafe = self.original_markupsafe
def test__was_markupsafe_imported(self):
"""
......@@ -52,8 +55,8 @@ class TemplateTestCase(unittest.TestCase):
self.assertEquals(bool(markupsafe), self._was_markupsafe_imported())
def test_init__escape__default_without_markupsafe(self):
template = Template()
self.assertEquals(template.escape(">'"), ">'")
renderer = Renderer()
self.assertEquals(renderer.escape(">'"), ">'")
def test_init__escape__default_with_markupsafe(self):
if not self._was_markupsafe_imported():
......@@ -61,73 +64,73 @@ class TemplateTestCase(unittest.TestCase):
return
self._restore_markupsafe()
template = Template()
self.assertEquals(template.escape(">'"), ">'")
renderer = Renderer()
self.assertEquals(renderer.escape(">'"), ">'")
def test_init__escape(self):
escape = lambda s: "foo" + s
template = Template(escape=escape)
self.assertEquals(template.escape("bar"), "foobar")
renderer = Renderer(escape=escape)
self.assertEquals(renderer.escape("bar"), "foobar")
def test_init__default_encoding__default(self):
"""
Check the default value.
"""
template = Template()
self.assertEquals(template.default_encoding, sys.getdefaultencoding())
renderer = Renderer()
self.assertEquals(renderer.default_encoding, sys.getdefaultencoding())
def test_init__default_encoding(self):
"""
Check that the constructor sets the attribute correctly.
"""
template = Template(default_encoding="foo")
self.assertEquals(template.default_encoding, "foo")
renderer = Renderer(default_encoding="foo")
self.assertEquals(renderer.default_encoding, "foo")
def test_init__decode_errors__default(self):
"""
Check the default value.
"""
template = Template()
self.assertEquals(template.decode_errors, 'strict')
renderer = Renderer()
self.assertEquals(renderer.decode_errors, 'strict')
def test_init__decode_errors(self):
"""
Check that the constructor sets the attribute correctly.
"""
template = Template(decode_errors="foo")
self.assertEquals(template.decode_errors, "foo")
renderer = Renderer(decode_errors="foo")
self.assertEquals(renderer.decode_errors, "foo")
def test_unicode(self):
template = Template()
actual = template.literal("abc")
renderer = Renderer()
actual = renderer.literal("abc")
self.assertEquals(actual, "abc")
self.assertEquals(type(actual), unicode)
def test_unicode__default_encoding(self):
template = Template()
renderer = Renderer()
s = "é"
template.default_encoding = "ascii"
self.assertRaises(UnicodeDecodeError, template.unicode, s)
renderer.default_encoding = "ascii"
self.assertRaises(UnicodeDecodeError, renderer.unicode, s)
template.default_encoding = "utf-8"
self.assertEquals(template.unicode(s), u"é")
renderer.default_encoding = "utf-8"
self.assertEquals(renderer.unicode(s), u"é")
def test_unicode__decode_errors(self):
template = Template()
renderer = Renderer()
s = "é"
template.default_encoding = "ascii"
template.decode_errors = "strict"
self.assertRaises(UnicodeDecodeError, template.unicode, s)
renderer.default_encoding = "ascii"
renderer.decode_errors = "strict"
self.assertRaises(UnicodeDecodeError, renderer.unicode, s)
template.decode_errors = "replace"
renderer.decode_errors = "replace"
# U+FFFD is the official Unicode replacement character.
self.assertEquals(template.unicode(s), u'\ufffd\ufffd')
self.assertEquals(renderer.unicode(s), u'\ufffd\ufffd')
def test_literal__with_markupsafe(self):
if not self._was_markupsafe_imported():
......@@ -135,39 +138,39 @@ class TemplateTestCase(unittest.TestCase):
return
self._restore_markupsafe()
_template = Template()
_template.default_encoding = "utf_8"
_renderer = Renderer()
_renderer.default_encoding = "utf_8"
# Check the standard case.
actual = _template.literal("abc")
actual = _renderer.literal("abc")
self.assertEquals(actual, "abc")
self.assertEquals(type(actual), template.markupsafe.Markup)
self.assertEquals(type(actual), renderer.markupsafe.Markup)
s = "é"
# Check that markupsafe respects default_encoding.
self.assertEquals(_template.literal(s), u"é")
_template.default_encoding = "ascii"
self.assertRaises(UnicodeDecodeError, _template.literal, s)
self.assertEquals(_renderer.literal(s), u"é")
_renderer.default_encoding = "ascii"
self.assertRaises(UnicodeDecodeError, _renderer.literal, s)
# Check that markupsafe respects decode_errors.
_template.decode_errors = "replace"
self.assertEquals(_template.literal(s), u'\ufffd\ufffd')
_renderer.decode_errors = "replace"
self.assertEquals(_renderer.literal(s), u'\ufffd\ufffd')
def test_render__unicode(self):
template = Template(u'foo')
actual = template.render()
renderer = Renderer()
actual = renderer.render(u'foo')
self.assertTrue(isinstance(actual, unicode))
self.assertEquals(actual, u'foo')
def test_render__str(self):
template = Template('foo')
actual = template.render()
renderer = Renderer()
actual = renderer.render('foo')
self.assertTrue(isinstance(actual, unicode))
self.assertEquals(actual, 'foo')
def test_render__non_ascii_character(self):
template = Template(u'Poincaré')
actual = template.render()
renderer = Renderer()
actual = renderer.render(u'Poincaré')
self.assertTrue(isinstance(actual, unicode))
self.assertEquals(actual, u'Poincaré')
......@@ -176,32 +179,33 @@ class TemplateTestCase(unittest.TestCase):
Test render(): passing a context.
"""
template = Template('Hi {{person}}')
self.assertEquals(template.render({'person': 'Mom'}), 'Hi Mom')
renderer = Renderer()
self.assertEquals(renderer.render('Hi {{person}}', {'person': 'Mom'}), 'Hi Mom')
def test_render__context_and_kwargs(self):
"""
Test render(): passing a context and **kwargs.
"""
template = Template('Hi {{person1}} and {{person2}}')
self.assertEquals(template.render({'person1': 'Mom'}, person2='Dad'), 'Hi Mom and Dad')
renderer = Renderer()
template = 'Hi {{person1}} and {{person2}}'
self.assertEquals(renderer.render(template, {'person1': 'Mom'}, person2='Dad'), 'Hi Mom and Dad')
def test_render__kwargs_and_no_context(self):
"""
Test render(): passing **kwargs and no context.
"""
template = Template('Hi {{person}}')
self.assertEquals(template.render(person='Mom'), 'Hi Mom')
renderer = Renderer()
self.assertEquals(renderer.render('Hi {{person}}', person='Mom'), 'Hi Mom')
def test_render__context_and_kwargs__precedence(self):
"""
Test render(): **kwargs takes precedence over context.
"""
template = Template('Hi {{person}}')
self.assertEquals(template.render({'person': 'Mom'}, person='Dad'), 'Hi Dad')
renderer = Renderer()
self.assertEquals(renderer.render('Hi {{person}}', {'person': 'Mom'}, person='Dad'), 'Hi Dad')
def test_render__kwargs_does_not_modify_context(self):
"""
......@@ -209,14 +213,14 @@ class TemplateTestCase(unittest.TestCase):
"""
context = {}
template = Template('Hi {{person}}')
template.render(context=context, foo="bar")
renderer = Renderer()
renderer.render('Hi {{person}}', context=context, foo="bar")
self.assertEquals(context, {})
def test_render__output_encoding(self):
template = Template(u'Poincaré')
template.output_encoding = 'utf-8'
actual = template.render()
renderer = Renderer()
renderer.output_encoding = 'utf-8'
actual = renderer.render(u'Poincaré')
self.assertTrue(isinstance(actual, str))
self.assertEquals(actual, 'Poincaré')
......@@ -225,29 +229,30 @@ class TemplateTestCase(unittest.TestCase):
Test passing a non-unicode template with non-ascii characters.
"""
template = Template("déf", output_encoding="utf-8")
renderer = Renderer(output_encoding="utf-8")
template = "déf"
# Check that decode_errors and default_encoding are both respected.
template.decode_errors = 'ignore'
template.default_encoding = 'ascii'
self.assertEquals(template.render(), "df")
renderer.decode_errors = 'ignore'
renderer.default_encoding = 'ascii'
self.assertEquals(renderer.render(template), "df")
template.default_encoding = 'utf_8'
self.assertEquals(template.render(), "déf")
renderer.default_encoding = 'utf_8'
self.assertEquals(renderer.render(template), "déf")
# By testing that Template.render() constructs the RenderEngine instance
# By testing that Renderer.render() constructs the RenderEngine instance
# correctly, we no longer need to test the rendering code paths through
# the Template. We can test rendering paths through only the RenderEngine
# the Renderer. We can test rendering paths through only the RenderEngine
# for the same amount of code coverage.
def test_make_render_engine__load_template(self):
"""
Test that _make_render_engine() passes the right load_template.
"""
template = Template()
template.load_template = "foo" # in real life, this would be a function.
renderer = Renderer()
renderer.load_template = "foo" # in real life, this would be a function.
engine = template._make_render_engine()
engine = renderer._make_render_engine()
self.assertEquals(engine.load_template, "foo")
def test_make_render_engine__literal(self):
......@@ -255,10 +260,10 @@ class TemplateTestCase(unittest.TestCase):
Test that _make_render_engine() passes the right literal.
"""
template = Template()
template.literal = "foo" # in real life, this would be a function.
renderer = Renderer()
renderer.literal = "foo" # in real life, this would be a function.
engine = template._make_render_engine()
engine = renderer._make_render_engine()
self.assertEquals(engine.literal, "foo")
def test_make_render_engine__escape(self):
......@@ -266,11 +271,11 @@ class TemplateTestCase(unittest.TestCase):
Test that _make_render_engine() passes the right escape.
"""
template = Template()
template.unicode = lambda s: s.upper() # a test version.
template.escape = lambda s: "**" + s # a test version.
renderer = Renderer()
renderer.unicode = lambda s: s.upper() # a test version.
renderer.escape = lambda s: "**" + s # a test version.
engine = template._make_render_engine()
engine = renderer._make_render_engine()
escape = engine.escape
self.assertEquals(escape(u"foo"), "**foo")
......
import unittest
import pystache
from pystache import Template
from pystache import Renderer
from examples.nested_context import NestedContext
from examples.complex_view import ComplexView
from examples.lambdas import Lambdas
......@@ -21,7 +21,8 @@ class TestSimple(unittest.TestCase):
def test_empty_context(self):
view = ComplexView()
self.assertEquals(pystache.Template('{{#empty_list}}Shouldnt see me {{/empty_list}}{{^empty_list}}Should see me{{/empty_list}}', view).render(), "Should see me")
template = '{{#empty_list}}Shouldnt see me {{/empty_list}}{{^empty_list}}Should see me{{/empty_list}}'
self.assertEquals(pystache.Renderer().render(template), "Should see me")
def test_callables(self):
view = Lambdas()
......@@ -38,8 +39,8 @@ class TestSimple(unittest.TestCase):
def test_non_existent_value_renders_blank(self):
view = Simple()
self.assertEquals(pystache.Template('{{not_set}} {{blank}}', view).render(), ' ')
template = '{{not_set}} {{blank}}'
self.assertEquals(pystache.Renderer().render(template), ' ')
def test_template_partial_extension(self):
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment