Skip to content

Instantly share code, notes, and snippets.

@pvinchon
Created September 28, 2017 10:55
Show Gist options
  • Save pvinchon/6444b16f9cd2b6368865fd6ca158ceb8 to your computer and use it in GitHub Desktop.
Save pvinchon/6444b16f9cd2b6368865fd6ca158ceb8 to your computer and use it in GitHub Desktop.
import argparse
import json
import os
from jinja2 import Environment, FileSystemLoader
def get_args():
def is_file(value):
if os.path.isfile(value): return value
raise argparse.ArgumentTypeError('file not found')
parser = argparse.ArgumentParser()
parser.add_argument('template', type=is_file, help='absolute path to jinja2 template')
parser.add_argument('--template-args-str', default='{}', help='a json object accessible in the template')
parser.add_argument('--template-args-file', type=is_file, help='absolute path to a file containing a json object accessible in the template')
return parser.parse_args()
if __name__ == "__main__":
args = get_args()
env = Environment(loader=FileSystemLoader('/'))
env.filters['jsonify'] = json.dumps
template = env.get_template(args.template)
data = {}
if args.template_args_str:
data.update(json.loads(args.template_args_str))
if args.template_args_file:
with open(args.template_args_file) as template_args_file:
data.update(json.load(template_args_file))
print template.render(**data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment