From de1c987c85d68f44a4d9d1b8e747dfb7c23d93a9 Mon Sep 17 00:00:00 2001 From: mike cullerton Date: Sat, 16 Oct 2021 14:17:53 -0400 Subject: [PATCH] New service to create and render template with Jinja Allows us to include Jinja templates within Jinja templates --- crc/services/jinja_service.py | 39 +++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 crc/services/jinja_service.py diff --git a/crc/services/jinja_service.py b/crc/services/jinja_service.py new file mode 100644 index 00000000..17671d48 --- /dev/null +++ b/crc/services/jinja_service.py @@ -0,0 +1,39 @@ +from jinja2 import Environment, DictLoader + + +class JinjaService: + """Service for Jinja2 templates. + +Includes the ability to embed templates inside templates, using task.data. + +-- In task.data +name = "Dan" +my_template = "Hi {{name}}, This is a jinja template too!" + +-- In Element Documentation +Please Introduce yourself. +{% include 'my_template' %} +Cool Right? + +-- Produces +Please Introduce yourself. +Hi Dan, This is a jinja template too! +Cool Right? +""" + + @staticmethod + def get_content(input_template, data): + templates = data + templates['main_template'] = input_template + jinja2_env = Environment(loader=DictLoader(templates)) + + try: + template = jinja2_env.get_template('main_template') + + except Exception: + # TODO: Should we deal w/ specific exceptions here? + # i.e., the ones in workflow_service._process_documentation + raise + + else: + return template.render(**data)