Skip to content

Instantly share code, notes, and snippets.

@rho333
Created April 25, 2018 23:13
Show Gist options
  • Save rho333/d0171566a0782eadcf27cedbe07f1546 to your computer and use it in GitHub Desktop.
Save rho333/d0171566a0782eadcf27cedbe07f1546 to your computer and use it in GitHub Desktop.
j2render - Python script to render Jinja2 templates on the CLI
#!/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