Skip to content

Instantly share code, notes, and snippets.

@noahmorrison
Created August 25, 2018 01:35
Show Gist options
  • Save noahmorrison/4810ee5cf33f694da2449952b9205809 to your computer and use it in GitHub Desktop.
Save noahmorrison/4810ee5cf33f694da2449952b9205809 to your computer and use it in GitHub Desktop.
Chevron custom data example
type: dog
mythical: false
"An ordinary animal"
type: kerberos
mythical: true
"A truly mythical creature!"
#!/usr/bin/env python
import chevron
class CustomData(dict):
class LowercaseBool:
_CHEVRON_return_scope_when_falsy = True
def __init__(self, value):
self.value = value
def __bool__(self):
return self.value
__nonzero__ = __bool__
def __str__(self):
if self.value:
return 'true'
return 'false'
def __into_custom(self,item):
if isinstance(item, dict):
return CustomData(item)
if isinstance(item, bool):
return self.LowercaseBool(item)
if isinstance(item, list):
return [self.__into_custom(i) for i in item]
return item
def __getitem__(self, key):
item = dict.__getitem__(self, key)
return self.__into_custom(item)
data = {
"entities": [
{
"type": "dog",
"mythical": False
},{
"type": "kerberos",
"mythical": True
}
],
"this_is_null": None
}
template = '''\
{{#entities}}
type: {{type}}
mythical: {{mythical}}
{{#mythical}}
"A truly mythical creature!"
{{/mythical}}
{{^mythical}}
"An ordinary animal"
{{/mythical}}
{{/entities}}
'''
data = CustomData(data)
print(chevron.render(template, data))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment