|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +# Copyright © 2012-2014 Roberto Alsina and others. |
| 4 | + |
| 5 | +# Permission is hereby granted, free of charge, to any |
| 6 | +# person obtaining a copy of this software and associated |
| 7 | +# documentation files (the "Software"), to deal in the |
| 8 | +# Software without restriction, including without limitation |
| 9 | +# the rights to use, copy, modify, merge, publish, |
| 10 | +# distribute, sublicense, and/or sell copies of the |
| 11 | +# Software, and to permit persons to whom the Software is |
| 12 | +# furnished to do so, subject to the following conditions: |
| 13 | +# |
| 14 | +# The above copyright notice and this permission notice |
| 15 | +# shall be included in all copies or substantial portions of |
| 16 | +# the Software. |
| 17 | +# |
| 18 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY |
| 19 | +# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE |
| 20 | +# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR |
| 21 | +# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS |
| 22 | +# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR |
| 23 | +# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR |
| 24 | +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE |
| 25 | +# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 26 | + |
| 27 | +"""Jinja template handlers""" |
| 28 | + |
| 29 | +import os |
| 30 | +import json |
| 31 | +from collections import deque |
| 32 | +try: |
| 33 | + import jinja2 |
| 34 | + from jinja2 import meta |
| 35 | +except ImportError: |
| 36 | + jinja2 = None # NOQA |
| 37 | +import pyjade |
| 38 | + |
| 39 | +from nikola.plugin_categories import TemplateSystem |
| 40 | +from nikola.utils import makedirs, req_missing |
| 41 | + |
| 42 | + |
| 43 | +class JinjaTemplates(TemplateSystem): |
| 44 | + """Wrapper for Jinja2 templates.""" |
| 45 | + |
| 46 | + name = "jinja" |
| 47 | + lookup = None |
| 48 | + dependency_cache = {} |
| 49 | + |
| 50 | + def __init__(self): |
| 51 | + """ initialize Jinja2 wrapper with extended set of filters""" |
| 52 | + if jinja2 is None: |
| 53 | + return |
| 54 | + self.lookup = jinja2.Environment(extensions=['pyjade.ext.jinja.PyJadeExtension']) |
| 55 | + self.lookup.filters['tojson'] = json.dumps |
| 56 | + self.lookup.filters['istuple'] = lambda x: isinstance(x, tuple) |
| 57 | + self.lookup.globals['enumerate'] = enumerate |
| 58 | + |
| 59 | + def set_directories(self, directories, cache_folder): |
| 60 | + """Create a template lookup.""" |
| 61 | + if jinja2 is None: |
| 62 | + req_missing(['jinja2'], 'use this theme') |
| 63 | + self.lookup.loader = jinja2.FileSystemLoader(directories, |
| 64 | + encoding='utf-8') |
| 65 | + |
| 66 | + def set_site(self, site): |
| 67 | + """Sets the site.""" |
| 68 | + self.site = site |
| 69 | + self.lookup.filters.update(self.site.config['TEMPLATE_FILTERS']) |
| 70 | + |
| 71 | + def render_template(self, template_name, output_name, context): |
| 72 | + """Render the template into output_name using context.""" |
| 73 | + if jinja2 is None: |
| 74 | + req_missing(['jinja2'], 'use this theme') |
| 75 | + if not template_name.endswith('.jade'): |
| 76 | + template_name = os.path.splitext(template_name)[0]+'.jade' |
| 77 | + template = self.lookup.get_template(template_name) |
| 78 | + output = template.render(**context) |
| 79 | + if output_name is not None: |
| 80 | + makedirs(os.path.dirname(output_name)) |
| 81 | + with open(output_name, 'w+') as output: |
| 82 | + output.write(output.encode('utf8')) |
| 83 | + return output |
| 84 | + |
| 85 | + def render_template_to_string(self, template, context): |
| 86 | + """Render template to a string using context.""" |
| 87 | + return self.lookup.from_string(template).render(**context) |
| 88 | + |
| 89 | + def template_deps(self, template_name): |
| 90 | + # Cache the lists of dependencies for each template name. |
| 91 | + if self.dependency_cache.get(template_name) is None: |
| 92 | + # Use a breadth-first search to find all templates this one |
| 93 | + # depends on. |
| 94 | + queue = deque([template_name]) |
| 95 | + visited_templates = set([template_name]) |
| 96 | + deps = [] |
| 97 | + while len(queue) > 0: |
| 98 | + curr = queue.popleft() |
| 99 | + source, filename = self.lookup.loader.get_source(self.lookup, |
| 100 | + curr)[:2] |
| 101 | + deps.append(filename) |
| 102 | + ast = self.lookup.parse(source) |
| 103 | + dep_names = meta.find_referenced_templates(ast) |
| 104 | + for dep_name in dep_names: |
| 105 | + if (dep_name not in visited_templates |
| 106 | + and dep_name is not None): |
| 107 | + visited_templates.add(dep_name) |
| 108 | + queue.append(dep_name) |
| 109 | + self.dependency_cache[template_name] = deps |
| 110 | + return self.dependency_cache[template_name] |
0 commit comments