Created
September 23, 2020 22:42
-
-
Save shmup/6ca901658b9da2034be1cc3dd9e65339 to your computer and use it in GitHub Desktop.
renders and prints a jinja2 template with optional json to STDOUT
This file contains hidden or 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 | |
# http://ix.io/2ykn/py | |
# renders and prints a jinja2 template with optional json to STDOUT | |
# requires: python3, jinja2 | |
# usage | |
# $ ./j2html /path/to/template | |
# $ ./j2html /path/to/template --json_data /path/to/json | |
from jinja2 import Environment, FileSystemLoader | |
from pathlib import Path | |
import argparse | |
import json | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser() | |
parser.add_argument('template', | |
help='jinja2 template to process', | |
type=argparse.FileType('r', encoding='UTF-8')) | |
parser.add_argument('--json_path', | |
help='json file passed to template', | |
type=argparse.FileType('r', encoding='UTF-8')) | |
args = parser.parse_args() | |
# load and parse json if provided | |
json_path = Path(args.json_path.name) if args.json_path else None | |
data = json.loads(json_path.read_text()) if json_path else {} | |
# load and render template | |
template_path = Path(args.template.name) | |
env = Environment( | |
loader=FileSystemLoader("{}/".format(template_path.parent))) | |
print(env.get_template(template_path.name).render(data)) | |
# close files, because ArgumentParser does not | |
args.template.close() | |
if args.json_path: | |
args.json_path.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment