Skip to content

Commit 99dfefc

Browse files
committed
templates: added ability to set custom template directory
Useful for custom projects outside of the s2e-env module.
1 parent 2ee7901 commit 99dfefc

File tree

1 file changed

+23
-18
lines changed

1 file changed

+23
-18
lines changed

s2e_env/utils/templates.py

+23-18
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,8 @@
2929
from .memoize import memoize
3030

3131

32-
TEMPLATES_DIR = os.path.join(os.path.dirname(__file__), '..', 'templates')
32+
DEFAULT_TEMPLATES_DIR = os.path.join(os.path.dirname(__file__), '..',
33+
'templates')
3334

3435

3536
def _datetimefilter(value, format_='%H:%M %d-%m-%Y'):
@@ -40,41 +41,45 @@ def _datetimefilter(value, format_='%H:%M %d-%m-%Y'):
4041

4142

4243
@memoize
43-
def _init_template_env(templates_dir=TEMPLATES_DIR):
44+
def _init_template_env(templates_dir=None):
4445
"""
4546
Initialize the jinja2 templating environment using the templates in the
4647
given directory.
4748
"""
49+
if not templates_dir:
50+
templates_dir = DEFAULT_TEMPLATES_DIR
51+
4852
env = Environment(loader=FileSystemLoader(templates_dir),
4953
autoescape=False, undefined=StrictUndefined)
5054
env.filters['datetimefilter'] = _datetimefilter
5155

5256
return env
5357

5458

55-
def render_template(context, template, path=None, executable=False):
59+
def render_template(context, template, output_path=None, templates_dir=None,
60+
executable=False):
5661
"""
5762
Renders the ``template`` template with the given ``context``. The result is
58-
written to ``path``. If ``path`` is not specified, the result is
59-
returned as a string
63+
returned as a string and written to ``output_path`` (if specified).
64+
65+
A directory containing the Jinja templates can optionally be specified.
6066
"""
61-
env = _init_template_env()
62-
data = env.get_template(template).render(context)
67+
env = _init_template_env(templates_dir)
68+
69+
rendered_data = env.get_template(template).render(context)
6370

6471
# Remove trailing spaces
6572
cleaned_lines = []
66-
for line in data.splitlines():
73+
for line in rendered_data.splitlines():
6774
cleaned_lines.append(line.rstrip())
68-
data = '\n'.join(cleaned_lines)
69-
70-
if not path:
71-
return data
75+
rendered_data = '\n'.join(cleaned_lines)
7276

73-
with open(path, 'w') as f:
74-
f.write(data)
77+
if output_path:
78+
with open(output_path, 'w') as f:
79+
f.write(rendered_data)
7580

76-
if executable:
77-
st = os.stat(path)
78-
os.chmod(path, st.st_mode | stat.S_IEXEC)
81+
if executable:
82+
st = os.stat(output_path)
83+
os.chmod(output_path, st.st_mode | stat.S_IEXEC)
7984

80-
return True
85+
return rendered_data

0 commit comments

Comments
 (0)