Created
April 25, 2018 23:13
-
-
Save rho333/d0171566a0782eadcf27cedbe07f1546 to your computer and use it in GitHub Desktop.
j2render - Python script to render Jinja2 templates on the CLI
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/local/bin/python | |
# To get all dependencies for this, run: | |
# pip install PyYAML jinja2 | |
# To install, just copy it to /usr/local/bin. | |
import sys, os | |
import jinja2 | |
import yaml | |
def render(tpl_path, context): | |
path, filename = os.path.split(tpl_path) | |
return jinja2.Environment( | |
loader=jinja2.FileSystemLoader(path or './') | |
).get_template(filename).render(context) | |
def usage(): | |
print(" j2render - Simple Jinja2 renderer \n") | |
print("Usage:\n") | |
print("j2render <template.anything> <context.yml> [-o | output.anything]\n") | |
print("Options:") | |
print(" -o: Print results directly to stdout, rather than writing to a file.") | |
sys.exit(1) | |
try: | |
if "-o" in sys.argv: | |
sys.argv.remove("-o") | |
print_to_term = True | |
else: | |
print_to_term = False | |
context = open(sys.argv[2], 'r') | |
context = yaml.load(context) | |
result = render(sys.argv[1], context) | |
if not print_to_term: | |
f = open(sys.argv[3], 'w') | |
f.write(result) | |
f.close() | |
else: | |
print(result) | |
except IndexError: | |
print("Missing an argument!") | |
usage() | |
except Exception as e: | |
print("An unexpected error occurred: " + str(e)) | |
usage() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment