Last active
September 25, 2024 14:50
-
-
Save lanefu/aa2dd52ce0b713abee0569a2e8571b54 to your computer and use it in GitHub Desktop.
simple python jinja2 template rendeer
This file contains 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
import os | |
from jinja2 import Environment, FileSystemLoader | |
import yaml | |
import argparse | |
import sys | |
from pathlib import Path | |
def render_template(template_path: Path, output_path: Path, var_values: dict) -> None: | |
""" | |
Render a Jinja2 template from a file and save it to the specified output path. | |
Args: | |
template_path (Path): The path of the input Jinja2 template file. | |
output_path (Path): The path where the rendered template will be saved. | |
var_values (dict): A dictionary containing variable values. | |
Returns: | |
None | |
""" | |
# Check if the template file exists | |
if not template_path.exists(): | |
print(f"Error: Template file '{template_path}' does not exist.") | |
sys.exit(1) | |
try: | |
# Create a Jinja2 environment with a loader for our templates | |
env = Environment(loader=FileSystemLoader(template_path.parent)) | |
# Load the template from the input file | |
template = env.get_template(template_path.name) | |
# Render the template and save it to the output path | |
with open(output_path, 'w') as f: | |
f.write(template.render(**var_values)) | |
except Exception as e: | |
print(f"Error rendering template: {e}") | |
sys.exit(1) | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser(description="Render a Jinja2 template from a file.") | |
parser.add_argument("--input", "-i", help="The path of the input Jinja2 template file.", required=True) | |
parser.add_argument("--output", "-o", help="The path where the rendered template will be saved.", required=True) | |
parser.add_argument("--vars", "-v", help="A YAML file containing variable values.", required=True) | |
args = parser.parse_args() | |
try: | |
with open(args.vars, 'r') as f: | |
var_values = yaml.safe_load(f) | |
except yaml.YAMLError as e: | |
print(f"Error loading YAML variables: {e}") | |
sys.exit(1) | |
render_template(Path(args.input), Path(args.output), var_values) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment