From: noah morrison Date: Thu, 9 Apr 2015 03:24:47 +0000 (-0400) Subject: Add support for complex types X-Git-Url: https://git.devinivas.org/?a=commitdiff_plain;h=75a139c061bb20107797f8c54a0c8eacf665b7bb;p=chevron.git Add support for complex types Before we were only allowing subscriptable structures, now we can take something subscriptable or more complex like a class with attributes. This *shouldn't* cause problems with builtins, but I'm not 100% sure. I've checked everything I could think of. I might want to make this opt-in at somepoint, if some people are having issues with it. --- diff --git a/chevron/renderer.py b/chevron/renderer.py index 7a3d93d..7ef8e28 100644 --- a/chevron/renderer.py +++ b/chevron/renderer.py @@ -57,17 +57,22 @@ def _get_key(key, scopes): # For every dot seperated key for child in key.split('.'): # Move into the scope - scope = scope[child] # Return the last scope we got # or an empty string if falsy + try: + # Try subscripting (Normal dictionaries) + scope = scope[child] + except (TypeError, AttributeError): + # Try the dictionary (Complex types) + scope = scope.__dict__[child] if scope is 0: return 0 if scope is False: return False return scope or '' - except (TypeError, KeyError): + except (AttributeError, KeyError): # We couldn't find the key in the current scope # We'll try again on the next pass pass diff --git a/test_spec.py b/test_spec.py index d5b0129..65084f4 100755 --- a/test_spec.py +++ b/test_spec.py @@ -156,6 +156,23 @@ class ExpandedCoverage(unittest.TestCase): self.assertEqual(result, expected) + def test_complex(self): + class Complex: + def __init__(self): + self.attr = 42 + + args = { + 'template': '{{comp.attr}} {{int.attr}}', + 'data': {'comp': Complex(), + 'int': 1 + } + } + + result = chevron.render(**args) + expected = '42 ' + + self.assertEqual(result, expected) + # Run unit tests from command line if __name__ == "__main__":