From fb29dabb590f729b1f3189d1d69a74ab63f7a70b Mon Sep 17 00:00:00 2001 From: Tim Den Ouden Date: Wed, 12 Jul 2023 19:08:21 -0700 Subject: [PATCH] Add parameterless callable variables --- chevron/renderer.py | 3 +++ test_spec.py | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/chevron/renderer.py b/chevron/renderer.py index 65a00f6..0208259 100644 --- a/chevron/renderer.py +++ b/chevron/renderer.py @@ -231,6 +231,9 @@ def render(template='', data={}, partials_path='.', partials_ext='mustache', elif tag == 'variable': # Add the html escaped key to the output thing = _get_key(key, scopes, warn=warn, keep=keep, def_ldel=def_ldel, def_rdel=def_rdel) + if isinstance(thing, Callable): + # if the variable is a callable function with no arguments (inspired by Mustache.js) get its value. + thing = thing() if thing is True and key == '.': # if we've coerced into a boolean by accident # (inverted tags do this) diff --git a/test_spec.py b/test_spec.py index 905e105..6b1a670 100755 --- a/test_spec.py +++ b/test_spec.py @@ -355,6 +355,27 @@ def function(content, render): expected = 'partial content' self.assertEqual(result, expected) + + def test_callable_variables(self): + '''Test callable variables + ''' + + def subject(): + return 'World' + + args = { + 'template': '{{greeting}} {{subject}}{{emphasis}}', + 'data': { + "greeting": 'Hello', + "subject": subject, + "emphasis": '!' + } + } + + result = chevron.render(**args) + expected = 'Hello World!' + + self.assertEqual(result, expected) # https://github.com/noahmorrison/chevron/issues/35 def test_custom_falsy(self):