diff --git a/chevron/renderer.py b/chevron/renderer.py index 65a00f6..cbb45c8 100644 --- a/chevron/renderer.py +++ b/chevron/renderer.py @@ -130,7 +130,7 @@ def _get_partial(name, partials_dict, partials_path, partials_ext): def render(template='', data={}, partials_path='.', partials_ext='mustache', partials_dict={}, padding='', def_ldel='{{', def_rdel='}}', - scopes=None, warn=False, keep=False): + scopes=None, warn=False, keep=False, serializer=str): """Render a mustache template. Renders a mustache template with a data scope and partial capability. @@ -179,6 +179,8 @@ def render(template='', data={}, partials_path='.', partials_ext='mustache', keep -- Keep unreplaced tags when a template substitution isn't found in the data + serializer -- Python data serializer (str by default) + Returns: @@ -237,7 +239,7 @@ def render(template='', data={}, partials_path='.', partials_ext='mustache', # then get the un-coerced object (next in the stack) thing = scopes[1] if not isinstance(thing, unicode_type): - thing = unicode(str(thing), 'utf-8') + thing = unicode(serializer(thing), 'utf-8') output += _html_escape(thing) # If we're a no html escape tag @@ -245,7 +247,7 @@ def render(template='', data={}, partials_path='.', partials_ext='mustache', # Just lookup the key and add it thing = _get_key(key, scopes, warn=warn, keep=keep, def_ldel=def_ldel, def_rdel=def_rdel) if not isinstance(thing, unicode_type): - thing = unicode(str(thing), 'utf-8') + thing = unicode(serializer(thing), 'utf-8') output += thing # If we're a section tag diff --git a/test_spec.py b/test_spec.py index 905e105..f689bb3 100755 --- a/test_spec.py +++ b/test_spec.py @@ -552,6 +552,21 @@ def test_keep_from_partials(self): expected = '1st {{ missing_key }} 3rd' self.assertEqual(result, expected) + def test_custom_serializer(self): + args = { + 'template': '{{ value }}', + 'data': { + 'value': { + 'key': None, + }, + }, + 'serializer': json.dumps, + } + + result = chevron.render(**args) + expected = '{"key": null}' + self.assertEqual(result, expected) + # Run unit tests from command line if __name__ == "__main__":