added a deprecation warning for a variable assignment, scope bug
Before adoption: this commit came in with the history the project adopted, so no landing records it.
that exists since 2.0, code could depend on. See :ref:`jinja-scoping-bug` for more information on this problem. Tip is 2.3 as this will be the next release (will happen soon!) --HG-- branch : trunk
authored by Armin Ronacher · committed by Armin Ronacher · parent f1c421d · Browse files · 7 files·+110 added−7 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+110 added−7 removed
- tests:+13 added−0 removed
- other:+97 added−7 removed
Provenance
- Commit
2b48839- Tree
b618331- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
f1c421d
7 files changed+110 added−7 removed
modified:docs/faq.rst+37 added
150 unmodified lines151 harder to maintain the code for older Python versions. If you really need152 Python 2.3 support you either have to use `Jinja 1`_ or other templating153 engines that still support 2.3.154 155+.. _jinja-scoping-bug:156+157+Scoping Bug in Jinja2158+---------------------159+160+Jinja2 currently has a scoping bug that causes confusing behavior. If you161+have a layout template that defines a macro, and a child template that162+does the same thing, it will see the macro from the layout template:163+164+layout.tmpl:165+166+.. sourcecode:: jinja167+168+ {% macro foo() %}LAYOUT{% endmacro %}169+ {% block body %}{% endblock %}170+171+child.tmpl:172+173+.. sourcecode:: jinja174+175+ {% extends 'layout.tmpl' %}176+ {% macro foo() %}CHILD{% endmacro %}177+ {% block body %}{{ foo() }}{% endblock %}178+179+This will print ``LAYOUT`` in Jinja2 versions older than 2.5. Starting180+with Jinja 2.2.2, there will however be a deprecation warning for this181+behavior. Starting with Jinja 2.5, this behavior will change so that182+``CHILD`` is printed instead.183+184+The reason why it was not changed right away is that some templates could185+depend on macros or variables defined in the layout template to be186+available in a child template. This however was undocumented behavior and187+is considered a bug.188+189+If you depend on this behavior, move your macros into a different file and190+import it into the layout and child template.191+192 .. _Jinja 1: http://jinja.pocoo.org/1/modified:jinja2/compiler.py+9 added-2 removed
723 unmodified lines724 # do we have an extends tag at all? If not, we can save some725 # overhead by just not processing any inheritance code.726 have_extends = node.find(nodes.Extends) is not None727 728+ # are there any block tags? If yes, we need a copy of the scope.729+ have_blocks = node.find(nodes.Block) is not None730+731 # find all blocks732 for block in node.find_all(nodes.Block):733 if block.name in self.blocks:734 self.fail('block %r defined twice' % block.name, block.lineno)24 unmodified lines759 frame.require_output_check = have_extends and not self.has_known_extends760 self.indent()761 if have_extends:762 self.writeline('parent_template = None')763+ if have_blocks:764+ self.writeline('block_context = context._block()')765 if 'self' in find_undeclared(node.body, ('self',)):766 frame.identifiers.add_special('self')767 self.writeline('l_self = TemplateReference(context)')768 self.pull_locals(frame)24 unmodified lines793 undeclared = find_undeclared(block.body, ('self', 'super'))794 if 'self' in undeclared:795 block_frame.identifiers.add_special('self')796 self.writeline('l_self = TemplateReference(context)')797+ if block.find(nodes.Block) is not None:798+ self.writeline('block_context = context._block(%r)' % name)799 if 'super' in undeclared:800 block_frame.identifiers.add_special('super')801 self.writeline('l_super = context.super(%r, '802 'block_%s)' % (name, name))22 unmodified lines825 self.writeline('if parent_template is None:')826 self.indent()827 level += 1828 if node.scoped:822- context = 'context.derived(locals())'829+ context = 'block_context.derived(locals())'830 else:824- context = 'context'831+ context = 'block_context'832 self.writeline('for event in context.blocks[%r][0](%s):' % (833 node.name, context), node)834 self.indent()835 self.simple_write('event', frame)703 unmodified linesmodified:jinja2/runtime.py+43 added
183 unmodified lines184 self.parent, True, None, locals)185 context.blocks.update((k, list(v)) for k, v in self.blocks.iteritems())186 return context187 188+ def _block(self, block=None):189+ """Creates a context that is used for block execution. Currently this190+ returns a special `_BlockContext` that warns about changed behavior.191+ In Jinja 2.5, this will instead just return a new context with the same192+ resolve behavior. Do not call from anywhere but the generated code!193+194+ :private:195+ """196+ return _BlockContext(self, block)197+198 def _all(meth):199 proxy = lambda self: getattr(self.get_all(), meth)()200 proxy.__doc__ = getattr(dict, meth).__doc__201 proxy.__name__ = meth29 unmodified lines231 self.name232 )233 234 235+class _BlockContext(Context):236+ """Implements a deprecation warning for the changed block assignments."""237+ __slots__ = ('real_context', 'block_name')238+239+ def __init__(self, real_context, block_name):240+ super(_BlockContext, self).__init__(real_context.environment,241+ real_context.parent,242+ real_context.name, {})243+ self.vars = dict(real_context.vars)244+ self.exported_vars = set(real_context.exported_vars)245+ self.blocks = real_context.blocks246+ self.real_context = real_context247+ self.block_name = block_name248+249+ def resolve(self, key):250+ self_rv = super(_BlockContext, self).resolve(key)251+ base_rv = self.real_context.resolve(key)252+ if self_rv != base_rv and not isinstance(base_rv, Undefined):253+ from warnings import warn254+ if self.block_name is not None:255+ detail = 'accessing %r from inside block %r' \256+ % (key, self.block_name)257+ else:258+ detail = 'accessing %r toplevel' % key259+ detail += ', in template %s' % self.name260+ warn(DeprecationWarning('variables set in a base template '261+ 'will no longer leak into the child '262+ 'context in future versions. Happened '263+ 'when ' + detail))264+ return base_rv265+ return self_rv266+267+268 # register the context as mapping if possible269 try:270 from collections import Mapping271 Mapping.register(Context)298 unmodified linesmodified:tests/test_old_bugs.py+13 added
10 unmodified lines11 from jinja2 import Environment, DictLoader, TemplateSyntaxError12 13 env = Environment()14 15+from nose import SkipTest16 from nose.tools import assert_raises17 18 19 def test_keyword_folding():55 unmodified lines75 def test_partial_conditional_assignments():76 tmpl = env.from_string('{% if b %}{% set a = 42 %}{% endif %}{{ a }}')77 assert tmpl.render(a=23) == '23'78 assert tmpl.render(b=True) == '42'79+80+81+def test_local_macros_first():82+ raise SkipTest('Behavior will change in 2.3')83+ env = Environment(loader=DictLoader({84+ 'layout.html': ('{% macro foo() %}LAYOUT{% endmacro %}'85+ '{% block body %}{% endblock %}'),86+ 'child.html': ('{% extends "layout.html" %}'87+ '{% macro foo() %}CHILD{% endmacro %}'88+ '{% block body %}{{ foo() }}{% endblock %}')89+ }))90+ assert env.get_template('child.html').render() == 'CHILD'modified:.hgignore+1 added-1 removed
1 unmodified line2 ^instance/3 ^jinja2/.*\.so$4 ^docs/_build5 ^(build|dist|Jinja2\.egg-info)/6-\.py[co]$6+\.py[cod]$7 \$py\.class$8 \.DS_Store$9 ^j?env/10 ^py3k/modified:CHANGES+6 added-3 removed
1 Jinja2 Changelog2 ================3 4-Version 2.2.25--------------6-(bugfix release, to be released soon)4+Version 2.35+-----------6+(codename Gnok, release date to be selected.)7 8 - fixes issue with code generator that causes unbound variables9 to be generated if set was used in if-blocks.10+- added a deprecation warning for a variable assignment, scope bug11+ that exists since 2.0, code could depend on. See :ref:`jinja-scoping-bug`12+ for more information on this problem.13 14 Version 2.2.115 -------------16 (bugfix release, released on September 14th 2009)114 unmodified linesmodified:setup.py+1 added-1 removed
47 unmodified lines48 49 50 setup(51 name='Jinja2',52- version='2.2.2',52+ version='2.3',53 url='http://jinja.pocoo.org/',54 license='BSD',55 author='Armin Ronacher',56 author_email='armin.ronacher@active-4.com',31 unmodified lines