Skip to content
Myr

track local loop/block vars for contextfunctions

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Amy · committed by Amy · parent fed1b24 · Browse files · 4 files+148 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

4 files+148 added−4 removed

  • tests:+98 added−0 removed
  • other:+50 added−4 removed

4 files+148 added−4 removed

modified:src/jinja2/compiler.py+37 added-4 removed
129 unmodified lines
130131 if parent is not None:132 self.buffer = parent.buffer133134 # variables set inside of loops and blocks should not affect outer frames,135 # but they still needs to be kept track of as part of the active context.136 self.loop_frame = False137 self.block_frame = False138139 def copy(self):140 """Create a copy of the current one."""141 rv = object.__new__(self.__class__)142 rv.__dict__.update(self.__dict__)
500 unmodified lines
643 """Pops the topmost level for assignment tracking and updates the644 context variables if necessary.645 """646 vars = self._assign_stack.pop()642 if not frame.toplevel or not vars:647 if (648 not frame.block_frame649 and not frame.loop_frame650 and not frame.toplevel651 or not vars652 ):653 return654 public_names = [x for x in vars if x[:1] != "_"]655 if len(vars) == 1:656 name = next(iter(vars))657 ref = frame.symbols.ref(name)658 if frame.loop_frame:659 self.writeline(f"_loop_vars[{name!r}] = {ref}")660 return661 if frame.block_frame:662 self.writeline(f"_block_vars[{name!r}] = {ref}")663 return664 self.writeline(f"context.vars[{name!r}] = {ref}")665 else:666 if frame.loop_frame:667 self.writeline("_loop_vars.update({")668 elif frame.block_frame:669 self.writeline("_block_vars.update({")670 else:650 self.writeline("context.vars.update({")671 self.writeline("context.vars.update({")672 for idx, name in enumerate(vars):673 if idx:674 self.write(", ")675 ref = frame.symbols.ref(name)676 self.write(f"{name!r}: {ref}")677 self.write("})")657 if public_names:678 if not frame.block_frame and not frame.loop_frame and public_names:679 if len(public_names) == 1:680 self.writeline(f"context.exported_vars.add({public_names[0]!r})")681 else:682 names_str = ", ".join(map(repr, public_names))
97 unmodified lines
780 # It's important that we do not make this frame a child of the781 # toplevel template. This would cause a variety of782 # interesting issues with identifier tracking.783 block_frame = Frame(eval_ctx)784 block_frame.block_frame = True785 undeclared = find_undeclared(block.body, ("self", "super"))786 if "self" in undeclared:787 ref = block_frame.symbols.declare_parameter("self")788 self.writeline(f"{ref} = TemplateReference(context)")
1 unmodified line
790 ref = block_frame.symbols.declare_parameter("super")791 self.writeline(f"{ref} = context.super({name!r}, block_{name})")792 block_frame.symbols.analyze_node(block)793 block_frame.block = name794 self.writeline("_block_vars = {}")795 self.enter_frame(block_frame)796 self.pull_dependencies(block.body)797 self.blockvisit(block.body, block_frame)798 self.leave_frame(block_frame, with_python_scope=True)
226 unmodified lines
1025 )10261027 def visit_For(self, node, frame):1028 loop_frame = frame.inner()1029 loop_frame.loop_frame = True1030 test_frame = frame.inner()1031 else_frame = frame.inner()10321033 # try to figure out if we have an extended loop. An extended loop
92 unmodified lines
11261127 self.indent()1128 self.enter_frame(loop_frame)11291130 self.writeline("_loop_vars = {}")1131 self.blockvisit(node.body, loop_frame)1132 if node.else_:1133 self.writeline(f"{iteration_indicator} = 0")1134 self.outdent()
300 unmodified lines
14351436 # -- Expression Visitors14371438 def visit_Name(self, node, frame):1414 if node.ctx == "store" and frame.toplevel:1439 if node.ctx == "store" and (1440 frame.toplevel or frame.loop_frame or frame.block_frame1441 ):1442 if self._assign_stack:1443 self._assign_stack[-1].add(node.name)1444 ref = frame.symbols.ref(node.name)1445
259 unmodified lines
1705 else:1706 self.write("context.call(")1707 self.visit(node.node, frame)1708 extra_kwargs = {"caller": "caller"} if forward_caller else None1709 loop_kwargs = {"_loop_vars": "_loop_vars"} if frame.loop_frame else {}1710 block_kwargs = {"_block_vars": "_block_vars"} if frame.block_frame else {}1711 if extra_kwargs:1712 extra_kwargs.update(loop_kwargs, **block_kwargs)1713 elif loop_kwargs or block_kwargs:1714 extra_kwargs = dict(loop_kwargs, **block_kwargs)1715 self.signature(node, frame, extra_kwargs)1716 self.write(")")1717 if self.environment.is_async:1718 self.write(")")
82 unmodified lines
modified:src/jinja2/runtime.py+9 added
282 unmodified lines
283 break284285 if callable(__obj):286 if getattr(__obj, "contextfunction", False) is True:287 # the active context should have access to variables set in288 # loops and blocks without mutating the context itself289 if kwargs.get("_loop_vars"):290 __self = __self.derived(kwargs["_loop_vars"])291 if kwargs.get("_block_vars"):292 __self = __self.derived(kwargs["_block_vars"])293 args = (__self,) + args294 elif getattr(__obj, "evalcontextfunction", False) is True:295 args = (__self.eval_ctx,) + args296 elif getattr(__obj, "environmentfunction", False) is True:297 args = (__self.environment,) + args298299 kwargs.pop("_block_vars", None)300 kwargs.pop("_loop_vars", None)301 try:302 return __obj(*args, **kwargs)303 except StopIteration:304 return __self.environment.undefined(
625 unmodified lines
modified:tests/test_regression.py+98 added
5 unmodified lines
6from jinja2 import Template7from jinja2 import TemplateAssertionError8from jinja2 import TemplateNotFound9from jinja2 import TemplateSyntaxError10from jinja2.utils import contextfunction111213class TestCorner:14 def test_assigned_scoping(self, env):
603 unmodified lines
618 from jinja2 import Markup619 from jinja2.runtime import ChainableUndefined620621 assert str(Markup(ChainableUndefined())) == ""622623 def test_scoped_block_loop_vars(self, env):624 tmpl = env.from_string(625 """\626Start627{% for i in ["foo", "bar"] -%}628{% block body scoped -%}629{{ loop.index }}) {{ i }}{% if loop.last %} last{% endif -%}630{%- endblock %}631{% endfor -%}632End"""633 )634 assert tmpl.render() == "Start\n1) foo\n2) bar last\nEnd"635636 def test_contextfunction_loop_vars(self, env):637 @contextfunction638 def test(ctx):639 return f"{ctx['i']}{ctx['j']}"640641 tmpl = env.from_string(642 """\643{% set i = 42 %}644{%- for idx in range(2) -%}645{{ i }}{{ j }}646{% set i = idx -%}647{%- set j = loop.index -%}648{{ test() }}649{{ i }}{{ j }}650{% endfor -%}651{{ i }}{{ j }}"""652 )653 tmpl.globals["test"] = test654 assert tmpl.render() == "42\n01\n01\n42\n12\n12\n42"655656 def test_contextfunction_scoped_loop_vars(self, env):657 @contextfunction658 def test(ctx):659 return f"{ctx['i']}"660661 tmpl = env.from_string(662 """\663{% set i = 42 %}664{%- for idx in range(2) -%}665{{ i }}666{%- set i = loop.index0 -%}667{% block body scoped %}668{{ test() }}669{% endblock -%}670{% endfor -%}671{{ i }}"""672 )673 tmpl.globals["test"] = test674 assert tmpl.render() == "42\n0\n42\n1\n42"675676 def test_contextfunction_in_blocks(self, env):677 @contextfunction678 def test(ctx):679 return f"{ctx['i']}"680681 tmpl = env.from_string(682 """\683{%- set i = 42 -%}684{{ i }}685{% block body -%}686{% set i = 24 -%}687{{ test() }}688{% endblock -%}689{{ i }}"""690 )691 tmpl.globals["test"] = test692 assert tmpl.render() == "42\n24\n42"693694 def test_contextfunction_block_and_loop(self, env):695 @contextfunction696 def test(ctx):697 return f"{ctx['i']}"698699 tmpl = env.from_string(700 """\701{%- set i = 42 -%}702{% for idx in range(2) -%}703{{ test() }}704{%- set i = idx -%}705{% block body scoped %}706{{ test() }}707{% set i = 24 -%}708{{ test() }}709{% endblock -%}710{{ test() }}711{% endfor -%}712{{ test() }}"""713 )714 tmpl.globals["test"] = test715716 # values set within a block or loop should not717 # show up outside of it718 assert tmpl.render() == "42\n0\n24\n0\n42\n1\n24\n1\n42"
modified:CHANGES.rst+4 added
30 unmodified lines
31 without a scheme are linked as ``https://`` instead of ``http://``.32 :issue:`522, 827, 1172`, :pr:`1195`33- Filters that get attributes, such as ``map`` and ``groupby``, can34 use a false or empty value as a default. :issue:`1331`35- Fix a bug that prevented variables set in blocks or loops from36 being accessed in custom context functions. :issue:`768`37- Fix a bug that caused scoped blocks from accessing special loop38 variables. :issue:`1088`394041Version 2.11.342--------------
780 unmodified lines