From: Daniel Morrison Date: Tue, 16 Apr 2019 23:03:15 +0000 (-0400) Subject: Implement indexed scopes #52 X-Git-Url: https://git.devinivas.org/?a=commitdiff_plain;h=3b439fd6c5808f2e6138844f4644e126d70abc1a;p=chevron.git Implement indexed scopes #52 --- diff --git a/chevron/renderer.py b/chevron/renderer.py index dd9c152..0d0d4b9 100644 --- a/chevron/renderer.py +++ b/chevron/renderer.py @@ -65,8 +65,12 @@ def _get_key(key, scopes): # Try subscripting (Normal dictionaries) scope = scope[child] except (TypeError, AttributeError): - # Try the dictionary (Complex types) - scope = scope.__dict__[child] + try: + # Try the dictionary (Complex types) + scope = scope.__dict__[child] + except: + # Try as a list + scope = scope[int(child)] # Return an empty string if falsy, with two exceptions # 0 should return 0, and False should return False @@ -82,7 +86,7 @@ def _get_key(key, scopes): return scope except AttributeError: return scope or '' - except (AttributeError, KeyError): + except (AttributeError, KeyError, IndexError): # 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 40befb6..72ef263 100755 --- a/test_spec.py +++ b/test_spec.py @@ -357,6 +357,21 @@ class ExpandedCoverage(unittest.TestCase): self.assertEqual(result, expected) + # https://github.com/noahmorrison/chevron/issues/52 + def test_indexed(self): + args = { + 'template': 'count {{count.0}}, {{count.1}}, ' + '{{count.100}}, {{nope.0}}', + 'data': { + "count": [5,4,3,2,1], + } + } + + result = chevron.render(**args) + expected = 'count 5, 4, , ' + + self.assertEqual(result, expected) + # Run unit tests from command line if __name__ == "__main__":