|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import argparse |
| 4 | +import json |
| 5 | +from jinja2 import Environment, FileSystemLoader |
| 6 | +import os |
| 7 | +import re |
| 8 | + |
| 9 | +# TODO: make this work for arbitrary context. ie. implement replace_using_context() |
| 10 | +def replace_placeholder(source_str, variable_name, variable_value): |
| 11 | + # Escaping any regex special characters in variable_name |
| 12 | + variable_name_escaped = re.escape(variable_name) |
| 13 | + |
| 14 | + # Using regular expression to replace ${variable_name} with actual variable_value |
| 15 | + # \s* means any amount of whitespace (including none) |
| 16 | + # pattern = rf'\$\{{\s*\{{\s*{variable_name_escaped}\s*\}}\s*\}}' |
| 17 | + pattern = rf'<<\s*{variable_name_escaped}\s*>>' |
| 18 | + return re.sub(pattern, variable_value.strip(), source_str) |
| 19 | + |
| 20 | +# Setup command-line argument parsing |
| 21 | +parser = argparse.ArgumentParser(description='Render a Jinja2 template using a JSON context.') |
| 22 | +parser.add_argument('template_file', type=str, help='Path to the Jinja2 template file (with .j2 extension).') |
| 23 | +parser.add_argument('json_file', type=str, help='Path to the JSON file to use as the rendering context.') |
| 24 | +parser.add_argument('output_file', type=str, help='Path to the output file.') |
| 25 | + |
| 26 | +args = parser.parse_args() |
| 27 | + |
| 28 | +# Load JSON file as the rendering context |
| 29 | +with open(args.json_file, 'r') as file: |
| 30 | + context = json.load(file) |
| 31 | + |
| 32 | +# Setup Jinja2 environment and load the template |
| 33 | +env = Environment( |
| 34 | + loader=FileSystemLoader(searchpath='./'), |
| 35 | + variable_start_string='<<', |
| 36 | + variable_end_string='>>', |
| 37 | + block_start_string='<%', |
| 38 | + block_end_string='%>', |
| 39 | + comment_start_string='<#', |
| 40 | + comment_end_string='#>') |
| 41 | +env.filters['replace_placeholder'] = replace_placeholder |
| 42 | + |
| 43 | +template = env.get_template(args.template_file) |
| 44 | + |
| 45 | +# Render the template with the context |
| 46 | +rendered_content = template.render(context) |
| 47 | +# print(rendered_content) |
| 48 | + |
| 49 | +with open(args.output_file, 'w') as file: |
| 50 | + file.write(rendered_content) |
| 51 | + |
| 52 | +print(f'Template rendered successfully. Output saved to {args.output_file}') |
0 commit comments