Merge branch 'override-codegen-context'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Markus Unterwaditzer · committed by Markus Unterwaditzer · parents a0d47b9, 8f7290a · Browse files · 6 files·+65 added−4 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+65 added−4 removed
- tests:+35 added−0 removed
- other:+30 added−4 removed
Provenance
- Commit
bd93bf3- Tree
208cbb3- Author
Markus Unterwaditzer <markus@unterwaditzer.net>- Committer
Markus Unterwaditzer <markus@unterwaditzer.net>- Parent 1
a0d47b9- Parent 2
8f7290a
6 files changed+65 added−4 removed
modified:docs/api.rst+13 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+ .. attribute:: context_class164+165+ The context used for templates. This should not be changed166+ in most cases, unless you need to modify internals of how167+ template variables are handled. For details, see168+ :class:`~jinja2.runtime.Context`.169+170 .. automethod:: overlay([options])171 172 .. method:: undefined([hint, obj, name, exc])173 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+10 added-2 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 generate25-from jinja2.runtime import Undefined, new_context24+from jinja2.compiler import generate, CodeGenerator25+from jinja2.runtime import Undefined, new_context, Context26 from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \27 TemplatesNotFound, TemplateRuntimeError28 from jinja2.utils import import_string, LRUCache, Markup, missing, \29 concat, consume, internalcode207 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+ #: the context class thatis used for templates. See246+ #: :class:`~jinja2.runtime.Context` for more information.247+ context_class = Context248+249 def __init__(self,250 block_start_string=BLOCK_START_STRING,251 block_end_string=BLOCK_END_STRING,252 variable_start_string=VARIABLE_START_STRING,961 unmodified linesmodified:jinja2/runtime.py+2 added-1 removed
67 unmodified lines68 parent = dict(parent)69 for key, value in iteritems(locals):70 if key[:2] == 'l_' and value is not missing:71 parent[key[2:]] = value72- return Context(environment, parent, template_name, blocks)72+ return environment.context_class(environment, parent, template_name,73+ blocks)74 75 76 class TemplateReference(object):77 """The `self` in templates."""590 unmodified linesmodified:tests/test_api.py+35 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.runtime import Context21 from jinja2.utils import Cycler22 23 24 @pytest.mark.api266 unmodified lines291 except UndefinedError as e:292 assert e.message == "'int object' has no attribute 'upper'"293 else:294 assert False, 'expected exception'295+296+297+@pytest.mark.api298+@pytest.mark.lowlevel299+class TestLowLevel():300+301+ def test_custom_code_generator(self):302+ class CustomCodeGenerator(CodeGenerator):303+ def visit_Const(self, node, frame=None):304+ # This method is pure nonsense, but works fine for testing...305+ if node.value == 'foo':306+ self.write(repr('bar'))307+ else:308+ super(CustomCodeGenerator, self).visit_Const(node, frame)309+310+ class CustomEnvironment(Environment):311+ code_generator_class = CustomCodeGenerator312+313+ env = CustomEnvironment()314+ tmpl = env.from_string('{% set foo = "foo" %}{{ foo }}')315+ assert tmpl.render() == 'bar'316+317+ def test_custom_context(self):318+ class CustomContext(Context):319+ def resolve(self, key):320+ return 'resolve-' + key321+322+ class CustomEnvironment(Environment):323+ context_class = CustomContext324+325+ env = CustomEnvironment()326+ tmpl = env.from_string('{{ foo }}')327+ assert tmpl.render() == 'resolve-foo'modified:CHANGES+3 added
24 unmodified lines25 - Added a check for default arguments followed by non-default arguments. This26 change makes ``{% macro m(x, y=1, z) %}...{% endmacro %}`` a syntax error. The27 previous behavior for this code was broken anyway (resulting in the default28 value being applied to `y`).29+- Add ability to use custom subclasses of ``jinja2.compiler.CodeGenerator`` and30+ ``jinja2.runtime.Context`` by adding two new attributes to the environment31+ (`code_generator_class` and `context_class`) (pull request ``#404``).32 33 Version 2.7.334 -------------35 (bugfix release, released on June 6th 2014)328 unmodified lines