]> Devi Nivas Git - chevron.git/commitdiff
Add support for complex types
authornoah morrison <noah@morrison.ph>
Thu, 9 Apr 2015 03:24:47 +0000 (23:24 -0400)
committernoah morrison <noah@morrison.ph>
Thu, 9 Apr 2015 03:24:47 +0000 (23:24 -0400)
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.

chevron/renderer.py
test_spec.py

index 7a3d93d410ae97c98375b5584052c9d8fff205ff..7ef8e2843774fc81208b966939b9cd41b1bfaca3 100644 (file)
@@ -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
index d5b01296367e09e42ea03ebe18cd1d33cbe93380..65084f429c9312b1a0e76978ac25da8d3c0e0a80 100755 (executable)
@@ -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__":