Last active
October 14, 2015 21:58
-
-
Save jonasfj/5b054ed546a5734c2009 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Alternative to None that is used to mark that something was optional and the | |
# slot in the container should be deleted. This is how we support optional | |
# properties | |
deleteMarker = {} | |
def renderString(string, params): | |
# Could also use pystache | |
for k,v in params.items(): | |
string = string.replace('{{' + k + '}}', v) | |
return string | |
def render(template, params): | |
if template is deleteMarker: | |
return template | |
elif isinstance(template, str): | |
return renderString(template, params) | |
elif isinstance(template, dict): | |
if '$if' in template: | |
if eval(template['$if']): | |
return render(template.get('then', deleteMarker), params) | |
else: | |
return render(template.get('else', deleteMarker), params) | |
if '$eval' in template: | |
return eval(template['$eval']) | |
retval = {} | |
for key, value in template.items(): | |
key = render(key, values) | |
value = render(value, values) | |
if value is not deleteMarker: | |
retval[key] = value | |
return retval | |
elif isinstance(template, list): | |
retval = [] | |
for i in template: | |
i = render(i, values) | |
# Allow for optional list entries | |
if i is not deleteMarker: | |
retval.append(i) | |
return retval | |
raise ValueError('Unsupported template: %s' % template) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
key being that
{"$if": "False", then: "not-happening"}
evaluates todeleteMarker
so
{prop1: "value", optionalProperty: {"$if": "False", then: "not-happening"}}
will render to{prop1: "value"}