Skip to content

Instantly share code, notes, and snippets.

@chalbersma
Last active June 9, 2020 04:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chalbersma/ae03561e90d4894519154aee1fb5329d to your computer and use it in GitHub Desktop.
Save chalbersma/ae03561e90d4894519154aee1fb5329d to your computer and use it in GitHub Desktop.
Python Jinja'ing Objects
#!/usr/bin/env python3
import time
import json
import jinja2
import yaml
const_date_yaml="""
---
twoweeks: "{{ twoweeksago }}"
hey: true
"""
unhydrated_config = yaml.safe_load(const_date_yaml)
dynam_vars = {"twoweeksago" : int(time.time()) - 604800*2}
if isinstance(unhydrated_config, str) is False:
# If it's a string
do_json = True
template = json.dumps(unhydrated_config, default=str)
else:
# Won't be ran in example
do_json = False
template = unhydrated_config
jtemplate = jinja2.Environment(loader=jinja2.BaseLoader).from_string(template)
rstring = jtemplate.render(**dynam_vars)
if do_json is True:
rendered = json.loads(rstring)
else:
# Not called in Example
rendered = rstring
print(rstring)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment