From f285f4aaae2a54cb35157eec7058b7941fcf3802 Mon Sep 17 00:00:00 2001 From: Chris Jerdonek Date: Sat, 20 Oct 2012 11:16:00 -0700 Subject: Address issue #130: allow string coercion to be customized. --- pystache/renderer.py | 35 ++++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) (limited to 'pystache/renderer.py') diff --git a/pystache/renderer.py b/pystache/renderer.py index 49be4a0..ff6a90c 100644 --- a/pystache/renderer.py +++ b/pystache/renderer.py @@ -23,11 +23,11 @@ class Renderer(object): A class for rendering mustache templates. This class supports several rendering options which are described in - the constructor's docstring. Among these, the constructor supports - passing a custom partial loader. + the constructor's docstring. Other behavior can be customized by + subclassing this class. - Here is an example of rendering a template using a custom partial loader - that loads partials from a string-string dictionary. + For example, one can pass a string-string dictionary to the constructor + to bypass loading partials from the file system: >>> partials = {'partial': 'Hello, {{thing}}!'} >>> renderer = Renderer(partials=partials) @@ -35,6 +35,16 @@ class Renderer(object): >>> print renderer.render('{{>partial}}', {'thing': 'world'}) Hello, world! + To customize string coercion (e.g. to render False values as ''), one can + subclass this class. For example: + + class MyRenderer(Renderer): + def str_coerce(self, val): + if not val: + return '' + else: + return str(val) + """ def __init__(self, file_encoding=None, string_encoding=None, @@ -146,6 +156,20 @@ class Renderer(object): """ return self._context + # We could not choose str() as the name because 2to3 renames the unicode() + # method of this class to str(). + def str_coerce(self, val): + """ + Coerce a non-string value to a string. + + This method is called whenever a non-string is encountered during the + rendering process when a string is needed (e.g. if a context value + for string interpolation is not a string). To customize string + coercion, you can override this method. + + """ + return str(val) + def _to_unicode_soft(self, s): """ Convert a basestring to unicode, preserving any unicode subclass. @@ -307,7 +331,8 @@ class Renderer(object): engine = RenderEngine(literal=self._to_unicode_hard, escape=self._escape_to_unicode, resolve_context=resolve_context, - resolve_partial=resolve_partial) + resolve_partial=resolve_partial, + to_str=self.str_coerce) return engine # TODO: add unit tests for this method. -- cgit v1.2.1