From 1309ef98877b80990acba0a386bbe555882c4649 Mon Sep 17 00:00:00 2001 From: Xavier Barbosa Date: Thu, 24 Oct 2013 11:10:13 +0200 Subject: [PATCH] fix jinja rendering of nested structures --- salt/utils/jinja.py | 8 +++++++- tests/unit/templates/jinja_test.py | 25 ++++++++++++++++++++++++- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/salt/utils/jinja.py b/salt/utils/jinja.py index 65004daabf..26ec77762f 100644 --- a/salt/utils/jinja.py +++ b/salt/utils/jinja.py @@ -21,6 +21,7 @@ import yaml import salt import salt.fileclient from salt.utils.odict import OrderedDict +from salt._compat import string_types log = logging.getLogger(__name__) @@ -129,7 +130,12 @@ class PrintableDict(OrderedDict): def __str__(self): output = [] for key, value in self.items(): - output.append('{0!r}: {1!r}'.format(str(key), str(value))) + if isinstance(value, string_types): + # keeps quotes around strings + output.append('{0!r}: {1!r}'.format(key, value)) + else: + # let default output + output.append('{0!r}: {1!s}'.format(key, value)) return '{' + ', '.join(output) + '}' def __repr__(self): # pylint: disable=W0221 diff --git a/tests/unit/templates/jinja_test.py b/tests/unit/templates/jinja_test.py index 2b0599d9de..540d00ce86 100644 --- a/tests/unit/templates/jinja_test.py +++ b/tests/unit/templates/jinja_test.py @@ -22,6 +22,7 @@ from salt.utils.templates import ( render_jinja_tmpl, get_template_context ) +from salt.utils.odict import OrderedDict # Import 3rd party libs import yaml @@ -351,7 +352,6 @@ class TestCustomExtensions(TestCase): with self.assertRaises(exceptions.TemplateRuntimeError): env.from_string('{% load_json as document %}{foo, bar: it works}{% endload %}').render() - def test_load_json(self): env = Environment(extensions=[SerializerExtension]) rendered = env.from_string('{% set document = \'{"foo": "it works"}\'|load_json %}' @@ -437,6 +437,29 @@ class TestCustomExtensions(TestCase): rendered = env.get_template('main6').render().strip() self.assertEqual(rendered, u"it works") + def test_nested_structures(self): + env = Environment(extensions=[SerializerExtension]) + rendered = env.from_string('{{ data }}').render(data="foo") + self.assertEquals(rendered, u"foo") + + rendered = env.from_string('{{ data }}').render(data=OrderedDict( + foo=OrderedDict( + bar='baz', + qux=42, + ) + )) + self.assertEquals(rendered, u"{'foo': {'bar': 'baz', 'qux': 42}}") + + rendered = env.from_string('{{ data }}').render(data=[ + OrderedDict( + foo='bar', + ), + OrderedDict( + baz=42, + ) + ]) + self.assertEquals(rendered, u"[{'foo': 'bar'}, {'baz': 2}]") + # def test_print(self): # env = Environment(extensions=[SerializerExtension]) # source = '{% import_yaml "toto.foo" as docu %}'