Let the Environment override the CodeGenerator
Before adoption: this commit came in with the history the project adopted, so no landing records it.
see #404
authored by ThiefMaster · committed by ThiefMaster · parent a0d47b9 · Browse files · 4 files·+35 added−2 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+35 added−2 removed
- tests:+22 added−0 removed
- other:+13 added−2 removed
Provenance
- Commit
1493631- Tree
2e33485- Author
ThiefMaster <adrian@planetcoding.net>- Committer
ThiefMaster <adrian@planetcoding.net>- Parent
a0d47b9
4 files changed+35 added−2 removed
modified:docs/api.rst+6 added
152 unmodified lines153 in a template. As long as no template was loaded it's safe154 to modify this dict. For more details see :ref:`global-namespace`.155 For valid object names have a look at :ref:`identifier-naming`.156 157+ .. attribute:: code_generator_class158+159+ The class used for code generation. This should not be changed160+ in most cases, unless you need to modify the Python code a161+ template compiles to.162+163 .. automethod:: overlay([options])164 165 .. method:: undefined([hint, obj, name, exc])166 635 unmodified linesmodified:jinja2/compiler.py+2 added-1 removed
55 unmodified lines56 defer_init=False):57 """Generate the python source for a node tree."""58 if not isinstance(node, nodes.Template):59 raise TypeError('Can\'t compile non template nodes')60- generator = CodeGenerator(environment, name, filename, stream, defer_init)60+ generator = environment.code_generator_class(environment, name, filename,61+ stream, defer_init)62 generator.visit(node)63 if stream is None:64 return generator.stream.getvalue()65 1599 unmodified linesmodified:jinja2/environment.py+5 added-1 removed
19 unmodified lines20 from jinja2.lexer import get_lexer, TokenStream21 from jinja2.parser import Parser22 from jinja2.nodes import EvalContext23 from jinja2.optimizer import optimize24-from jinja2.compiler import generate24+from jinja2.compiler import generate, CodeGenerator25 from jinja2.runtime import Undefined, new_context26 from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \27 TemplatesNotFound, TemplateRuntimeError28 from jinja2.utils import import_string, LRUCache, Markup, missing, \208 unmodified lines237 #: these are currently EXPERIMENTAL undocumented features.238 exception_handler = None239 exception_formatter = None240 241+ #: the class that is used for code generation. See242+ #: :class:`~jinja2.compiler.CodeGenerator` for more information.243+ code_generator_class = CodeGenerator244+245 def __init__(self,246 block_start_string=BLOCK_START_STRING,247 block_end_string=BLOCK_END_STRING,248 variable_start_string=VARIABLE_START_STRING,961 unmodified linesmodified:tests/test_api.py+22 added
14 unmodified lines15 import pytest16 from jinja2 import Environment, Undefined, DebugUndefined, \17 StrictUndefined, UndefinedError, meta, \18 is_undefined, Template, DictLoader, make_logging_undefined19+from jinja2.compiler import CodeGenerator20 from jinja2.utils import Cycler21 22 23 @pytest.mark.api266 unmodified lines290 except UndefinedError as e:291 assert e.message == "'int object' has no attribute 'upper'"292 else:293 assert False, 'expected exception'294+295+296+@pytest.mark.api297+@pytest.mark.lowlevel298+class TestLowLevel():299+300+ def test_custom_code_generator(self):301+ class CustomCodeGenerator(CodeGenerator):302+ def visit_Const(self, node, frame=None):303+ # This method is pure nonsense, but works fine for testing...304+ if node.value == 'foo':305+ self.write(repr('bar'))306+ else:307+ super(CustomCodeGenerator, self).visit_Const(node, frame)308+309+ class CustomEnvironment(Environment):310+ code_generator_class = CustomCodeGenerator311+312+ env = CustomEnvironment()313+ tmpl = env.from_string('{% set foo = "foo" %}{{ foo }}')314+ assert tmpl.render() == 'bar'