| 1 |
from functools import wraps |
| 2 |
|
| 3 |
from markupsafe import Markup |
| 4 |
from jinja2 import Environment |
| 5 |
from jinja2.compiler import CodeGenerator |
| 6 |
|
| 7 |
|
| 8 |
class LocalOverridingCodeGenerator(CodeGenerator): |
| 9 |
def visit_Template(self, *args, **kwargs): |
| 10 |
super(LocalOverridingCodeGenerator, self).visit_Template(*args, |
| 11 |
**kwargs) |
| 12 |
overrides = getattr(self.environment, '_codegen_overrides', {}) |
| 13 |
|
| 14 |
if overrides: |
| 15 |
self.writeline('') |
| 16 |
|
| 17 |
for name, override in overrides.items(): |
| 18 |
self.writeline('{} = {}'.format(name, override)) |
| 19 |
|
| 20 |
|
| 21 |
class DynAutoEscapeEnvironment(Environment): |
| 22 |
code_generator_class = LocalOverridingCodeGenerator |
| 23 |
|
| 24 |
def __init__(self, *args, **kwargs): |
| 25 |
escape_func = kwargs.pop('escape_func', None) |
| 26 |
markup_class = kwargs.pop('markup_class', None) |
| 27 |
|
| 28 |
super(DynAutoEscapeEnvironment, self).__init__(*args, **kwargs) |
| 29 |
|
| 30 |
# we need to disable constant-evaluation at compile time, because it |
| 31 |
# calls jinja's own escape function. |
| 32 |
# |
| 33 |
# this is done by jinja itself if a finalize function is set and it |
| 34 |
# is marked as a contextfunction. this is accomplished by either |
| 35 |
# suppling a no-op contextfunction itself or wrapping an existing |
| 36 |
# finalize in a contextfunction |
| 37 |
if self.finalize: |
| 38 |
if not getattr(self.finalize, 'contextfunction', False): |
| 39 |
_finalize = getattr(self, 'finalize') |
| 40 |
self.finalize = lambda _, v: _finalize(v) |
| 41 |
else: |
| 42 |
self.finalize = lambda _, v: v |
| 43 |
self.finalize.contextfunction = True |
| 44 |
|
| 45 |
self._codegen_overrides = {} |
| 46 |
|
| 47 |
if escape_func: |
| 48 |
self._codegen_overrides['escape'] = 'environment.escape_func' |
| 49 |
self.escape_func = escape_func |
| 50 |
self.filters['e'] = escape_func |
| 51 |
self.filters['escape'] = escape_func |
| 52 |
|
| 53 |
if markup_class: |
| 54 |
self._codegen_overrides['markup'] = 'environment.markup_class' |
| 55 |
self.markup_class = markup_class |
| 56 |
|
| 57 |
|
| 58 |
def markup_escape_func(f): |
| 59 |
@wraps(f) |
| 60 |
def _(v): |
| 61 |
if isinstance(v, Markup): |
| 62 |
return v |
| 63 |
return Markup(f(v)) |
| 64 |
|
| 65 |
return _ |