Skip to content

Commit abc6fda

Browse files
committed
Parse ansible '#jinja2:' overrides
1 parent c540c4c commit abc6fda

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

jinja2cli/cli.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
import os
1313
import sys
14+
import ast
1415
from optparse import Option, OptionParser
1516

1617
sys.path.insert(0, os.getcwd())
@@ -273,7 +274,26 @@ def render(template_path, data, extensions, strict=False):
273274
env.globals["environ"] = lambda key: force_text(os.environ.get(key))
274275
env.globals["get_context"] = lambda: data
275276

276-
return env.get_template(os.path.basename(template_path)).render(data)
277+
# parse ansible jinja2 overrides
278+
JINJA2_OVERRIDE = '#jinja2:'
279+
with open(template_path, 'r') as f:
280+
template = f.read()
281+
if template.startswith(JINJA2_OVERRIDE):
282+
eol = template.find('\n')
283+
line = template[len(JINJA2_OVERRIDE):eol]
284+
template = template[eol + 1:]
285+
for pair in line.split(','):
286+
if ':' not in pair:
287+
raise RuntimeError("failed to parse jinja2 override '%s'."
288+
" Did you use something different from colon as key-value separator?" % pair.strip())
289+
(key, val) = pair.split(':', 1)
290+
key = key.strip()
291+
if hasattr(env, key):
292+
setattr(env, key, ast.literal_eval(val.strip()))
293+
else:
294+
print(f"Could not find Jinja2 environment setting to override: '{key}'", file=sys.stderr)
295+
296+
return env.from_string(template).render(data)
277297

278298

279299
def is_fd_alive(fd):

0 commit comments

Comments
 (0)