Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Jinja2 - Config Template
import argparse
import errno
import os
import sys
from jinja2 import Environment, FileSystemLoader, StrictUndefined
UTF8 = 'utf8'
TEMPLATE = 'template'
def parse_option(sys_args):
parser = argparse.ArgumentParser(
description='Generate a configuration combining templates',
formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument('--input_folder', '-i', required=True, help='Input folder')
parser.add_argument('--output_folder', '-o', required=True, help='Output folder')
return parser, parser.parse_args(sys_args)
def create_directory(filename):
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
def chop(value, ending):
if value.endswith(ending):
return value[:-len(ending)]
return value
def generate_template(template, output_folder):
template_content = template.render(os.environ)
target_file = os.path.join(output_folder, template.name)
target_file = chop(target_file, '.template')
create_directory(target_file)
with open(target_file, 'w') as writer:
writer.write(template_content)
def main(args=None):
if args is None:
args = sys.argv[1:]
parser, args = parse_option(args)
file_system_loader = FileSystemLoader(args.input_folder)
env = Environment(
loader=file_system_loader,
undefined=StrictUndefined # Fails if it tries to render undefined values
)
templates = [env.get_template(template_path) for template_path in env.list_templates()
if template_path.endswith(TEMPLATE) or TEMPLATE not in template_path]
for template in templates:
generate_template(template, args.output_folder)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.