Skip to content
Myr

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

7 files+110 added−7 removed

modified:docs/faq.rst+37 added
150 unmodified lines
151harder to maintain the code for older Python versions. If you really need152Python 2.3 support you either have to use `Jinja 1`_ or other templating153engines that still support 2.3.154155.. _jinja-scoping-bug:156157Scoping Bug in Jinja2158---------------------159160Jinja2 currently has a scoping bug that causes confusing behavior. If you161have a layout template that defines a macro, and a child template that162does the same thing, it will see the macro from the layout template:163164layout.tmpl:165166.. sourcecode:: jinja167168 {% macro foo() %}LAYOUT{% endmacro %}169 {% block body %}{% endblock %}170171child.tmpl:172173.. sourcecode:: jinja174175 {% extends 'layout.tmpl' %}176 {% macro foo() %}CHILD{% endmacro %}177 {% block body %}{{ foo() }}{% endblock %}178179This will print ``LAYOUT`` in Jinja2 versions older than 2.5. Starting180with Jinja 2.2.2, there will however be a deprecation warning for this181behavior. Starting with Jinja 2.5, this behavior will change so that182``CHILD`` is printed instead.183184The reason why it was not changed right away is that some templates could185depend on macros or variables defined in the layout template to be186available in a child template. This however was undocumented behavior and187is considered a bug.188189If you depend on this behavior, move your macros into a different file and190import it into the layout and child template.191192.. _Jinja 1: http://jinja.pocoo.org/1/
modified:jinja2/compiler.py+9 added-2 removed
723 unmodified lines
724 # 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 None727728 # are there any block tags? If yes, we need a copy of the scope.729 have_blocks = node.find(nodes.Block) is not None730731 # 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 lines
759 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 lines
793 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 lines
825 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 lines
modified:jinja2/runtime.py+43 added
183 unmodified lines
184 self.parent, True, None, locals)185 context.blocks.update((k, list(v)) for k, v in self.blocks.iteritems())186 return context187188 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!193194 :private:195 """196 return _BlockContext(self, block)197198 def _all(meth):199 proxy = lambda self: getattr(self.get_all(), meth)()200 proxy.__doc__ = getattr(dict, meth).__doc__201 proxy.__name__ = meth
29 unmodified lines
231 self.name232 )233234235class _BlockContext(Context):236 """Implements a deprecation warning for the changed block assignments."""237 __slots__ = ('real_context', 'block_name')238239 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_name248249 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_rv266267268# register the context as mapping if possible269try:270 from collections import Mapping271 Mapping.register(Context)
298 unmodified lines
modified:tests/test_old_bugs.py+13 added
10 unmodified lines
11from jinja2 import Environment, DictLoader, TemplateSyntaxError1213env = Environment()1415from nose import SkipTest16from nose.tools import assert_raises171819def test_keyword_folding():
55 unmodified lines
75def 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'798081def 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 line
2^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
1Jinja2 Changelog2================34Version 2.2.25-------------6(bugfix release, to be released soon)4Version 2.35-----------6(codename Gnok, release date to be selected.)78- 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.1314Version 2.2.115-------------16(bugfix release, released on September 14th 2009)
114 unmodified lines
modified:setup.py+1 added-1 removed
47 unmodified lines
484950setup(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