diff --git a/jinja2cli/cli.py b/jinja2cli/cli.py index 3c2f633..9b5e0d5 100644 --- a/jinja2cli/cli.py +++ b/jinja2cli/cli.py @@ -11,6 +11,7 @@ import os import sys +import ast from optparse import Option, OptionParser sys.path.insert(0, os.getcwd()) @@ -246,7 +247,7 @@ def render(template_path, data, extensions, strict=False): from jinja2 import ( __version__ as jinja_version, Environment, - FileSystemLoader, + BaseLoader, StrictUndefined, ) @@ -262,7 +263,7 @@ def render(template_path, data, extensions, strict=False): extensions.append(ext) env = Environment( - loader=FileSystemLoader(os.path.dirname(template_path)), + loader=BaseLoader(), extensions=extensions, keep_trailing_newline=True, ) @@ -273,7 +274,23 @@ def render(template_path, data, extensions, strict=False): env.globals["environ"] = lambda key: force_text(os.environ.get(key)) env.globals["get_context"] = lambda: data - return env.get_template(os.path.basename(template_path)).render(data) + # parse ansible jinja2 overrides + JINJA2_OVERRIDE = '#jinja2:' + with open(template_path, 'r') as f: + template = f.read() + if template.startswith(JINJA2_OVERRIDE): + eol = template.find('\n') + line = template[len(JINJA2_OVERRIDE):eol] + template = template[eol + 1:] + for pair in line.split(','): + if ':' not in pair: + raise RuntimeError("failed to parse jinja2 override '%s'." + " Did you use something different from colon as key-value separator?" % pair.strip()) + (key, val) = pair.split(':', 1) + key = key.strip() + setattr(env, key, ast.literal_eval(val.strip())) + + return env.from_string(template).render(data) def is_fd_alive(fd):