from website_generator.fields import PathMatcherField, PathField from website_generator.config import ActionConfig from website_generator.actions import Action from jinja2 import Environment, FilesystemLoader, select_autoescape import typesystem class JinjaActionConfig(ActionConfig): template = PathMatcherField() dest = PathField(allow_null=True, must_exist=False, allow_folders=True) environment = typesystem.Object(additional_properties=True, default=dict) class JinjaAction(Action): type = 'jinja2' def __init__(self, **params): config = JinjaActionConfig.validate(params) params['template'] = config.template params['dest'] = config.dest super().__init__(**params) def build_environment(self): """ Build a Jinja2 environment for templates. """ return Environment( loader=FilesystemLoader(self.main_config.content_root), ) def render_template(self, env, template_path, dest_path): template = env.get_template(template_path) def __call__(self): env = self.build_environment() if self.dest.is_dir() or str(self.dest).endswith('/'): self.dest.mkdir(parents=True, exist_ok=True) for template_path in self.src.all(): self.render_template(env, template_path, self.dest / template_path.name) else: template_path = template = env.get_template(template_path)