1
|
|
|
# -*- coding: utf-8 -*- |
2
|
|
|
|
3
|
|
|
from jinja2 import Environment, StrictUndefined |
4
|
|
|
|
5
|
|
|
from .exceptions import UnknownExtension |
6
|
|
|
|
7
|
|
|
|
8
|
|
|
class ExtensionLoaderMixin(object): |
9
|
|
|
"""Mixin that provides a sane way of loading extensions specified in a |
10
|
|
|
given context. |
11
|
|
|
|
12
|
|
|
The context is being extracted from the keyword arguments before calling |
13
|
|
|
the next parent class in line of the child. |
14
|
|
|
""" |
15
|
|
|
def __init__(self, **kwargs): |
16
|
|
|
context = kwargs.pop('context', {}) |
17
|
|
|
|
18
|
|
|
default_extensions = [ |
19
|
|
|
'jinja2_time.TimeExtension', |
20
|
|
|
] |
21
|
|
|
extensions = default_extensions + self._read_extensions(context) |
22
|
|
|
|
23
|
|
|
try: |
24
|
|
|
super(ExtensionLoaderMixin, self).__init__( |
25
|
|
|
extensions=extensions, |
26
|
|
|
**kwargs |
27
|
|
|
) |
28
|
|
|
except ImportError as err: |
29
|
|
|
raise UnknownExtension('Unable to load extension: {}'.format(err)) |
30
|
|
|
|
31
|
|
|
def _read_extensions(self, context): |
32
|
|
|
"""Return a list of extensions as str to be passed on to the jinja2 |
33
|
|
|
env. If context does not contain the relevant info, return an empty |
34
|
|
|
list instead. |
35
|
|
|
""" |
36
|
|
|
try: |
37
|
|
|
extensions = context['cookiecutter']['_extensions'] |
38
|
|
|
except KeyError: |
39
|
|
|
return [] |
40
|
|
|
else: |
41
|
|
|
return [str(ext) for ext in extensions] |
42
|
|
|
|
43
|
|
|
|
44
|
|
|
class StrictEnvironment(ExtensionLoaderMixin, Environment): |
45
|
|
|
"""Jinja2 environment that raises an error when it hits a variable |
46
|
|
|
which is not defined in the context used to render a template. |
47
|
|
|
""" |
48
|
|
|
def __init__(self, **kwargs): |
49
|
|
|
super(StrictEnvironment, self).__init__( |
50
|
|
|
undefined=StrictUndefined, |
51
|
|
|
**kwargs |
52
|
|
|
) |
53
|
|
|
|