diff options
| author | 2012-12-12 19:58:42 -0300 | |
|---|---|---|
| committer | 2012-12-12 19:58:42 -0300 | |
| commit | ca1f5a392261a7c6b82b5ac1015427605909d8c9 (patch) | |
| tree | f91146c9340c6c78e84aaf6b92053386397e2069 /nikola/mako_templates.py | |
Imported Upstream version 4.0.3upstream/4.0.3
Diffstat (limited to 'nikola/mako_templates.py')
| -rw-r--r-- | nikola/mako_templates.py | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/nikola/mako_templates.py b/nikola/mako_templates.py new file mode 100644 index 0000000..e4a79d9 --- /dev/null +++ b/nikola/mako_templates.py @@ -0,0 +1,65 @@ +######################################## +# Mako template handlers +######################################## + +import os +import shutil + +from mako import util, lexer +from mako.lookup import TemplateLookup + +lookup = None +cache = {} + + +def get_deps(filename): + text = util.read_file(filename) + lex = lexer.Lexer(text=text, filename=filename) + lex.parse() + + deps = [] + for n in lex.template.nodes: + if getattr(n, 'keyword', None) == "inherit": + deps.append(n.attributes['file']) + # TODO: include tags are not handled + return deps + + +def get_template_lookup(directories): + cache_dir = os.path.join('cache', '.mako.tmp') + if os.path.exists(cache_dir): + shutil.rmtree(cache_dir) + return TemplateLookup( + directories=directories, + module_directory=cache_dir, + output_encoding='utf-8', + ) + + +def render_template(template_name, output_name, context, global_context): + template = lookup.get_template(template_name) + local_context = {} + local_context.update(global_context) + local_context.update(context) + data = template.render_unicode(**local_context) + if output_name is not None: + try: + os.makedirs(os.path.dirname(output_name)) + except: + pass + with open(output_name, 'w+') as output: + output.write(data) + return data + + +def template_deps(template_name): + # We can cache here because depedencies should + # not change between runs + if cache.get(template_name, None) is None: + template = lookup.get_template(template_name) + dep_filenames = get_deps(template.filename) + deps = [template.filename] + for fname in dep_filenames: + deps += template_deps(fname) + cache[template_name] = tuple(deps) + return list(cache[template_name]) |
