29
29
from .memoize import memoize
30
30
31
31
32
- TEMPLATES_DIR = os .path .join (os .path .dirname (__file__ ), '..' , 'templates' )
32
+ DEFAULT_TEMPLATES_DIR = os .path .join (os .path .dirname (__file__ ), '..' ,
33
+ 'templates' )
33
34
34
35
35
36
def _datetimefilter (value , format_ = '%H:%M %d-%m-%Y' ):
@@ -40,41 +41,45 @@ def _datetimefilter(value, format_='%H:%M %d-%m-%Y'):
40
41
41
42
42
43
@memoize
43
- def _init_template_env (templates_dir = TEMPLATES_DIR ):
44
+ def _init_template_env (templates_dir = None ):
44
45
"""
45
46
Initialize the jinja2 templating environment using the templates in the
46
47
given directory.
47
48
"""
49
+ if not templates_dir :
50
+ templates_dir = DEFAULT_TEMPLATES_DIR
51
+
48
52
env = Environment (loader = FileSystemLoader (templates_dir ),
49
53
autoescape = False , undefined = StrictUndefined )
50
54
env .filters ['datetimefilter' ] = _datetimefilter
51
55
52
56
return env
53
57
54
58
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 ):
56
61
"""
57
62
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.
60
66
"""
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 )
63
70
64
71
# Remove trailing spaces
65
72
cleaned_lines = []
66
- for line in data .splitlines ():
73
+ for line in rendered_data .splitlines ():
67
74
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 )
72
76
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 )
75
80
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 )
79
84
80
- return True
85
+ return rendered_data
0 commit comments