Last active
June 9, 2020 04:21
-
-
Save chalbersma/ae03561e90d4894519154aee1fb5329d to your computer and use it in GitHub Desktop.
Python Jinja'ing Objects
This file contains 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
#!/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