Last active
January 27, 2019 23:16
-
-
Save schuerg/0db3f45af93a995aa4ca253b29323edb to your computer and use it in GitHub Desktop.
[Render Jinja2 template from terminal] Renders a given Jinja2 template and saves it as a new file. #python #jinja2
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 python | |
# -*- coding: utf-8 -*- | |
# | |
# This script renders a given Jinja2 template and saves it as a new file. | |
# | |
# Simon Schürg | |
import argparse | |
import os | |
from pathlib import Path | |
from jinja2 import Environment, FileSystemLoader | |
def setupArgparse(): | |
parser = argparse.ArgumentParser(description='Renders a given Jinja2 template and saves it as a new file.') | |
parser.add_argument('template', metavar='TEMPLATE', help='Jinja2 template file path') | |
parser.add_argument('output', metavar='OUTPUT', help='Output file path') | |
parser.add_argument('vars', metavar='VARS', help='Variables to apply to the template (as <var>=<value>)', nargs='*') | |
# parser.add_argument('-v', '--verbose', action='count', help='Verbose output') | |
args = parser.parse_args() | |
template_vars = {} | |
for template_var in args.vars: | |
key, value = template_var.strip().split("=") | |
template_vars[key]=value | |
return args, template_vars | |
def setupJinja2(args): | |
if not Path(args.template).is_file(): | |
print("The given template {} is no file!".format(args.template)) | |
exit(1) | |
template_dir = os.path.dirname(args.template) | |
env = Environment(loader=FileSystemLoader(template_dir)) | |
return env | |
if __name__ == "__main__": | |
args, template_vars = setupArgparse() | |
env = setupJinja2(args) | |
template = env.get_template(os.path.basename(args.template)) | |
parsed_template = template.render(**template_vars) | |
print(parsed_template) | |
with open(args.output, "w") as output_file: | |
output_file.write(parsed_template) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment