Skip to content
Myr

fix f-string syntax error in code generation (#1852)

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

authored by David Lord · committed by GitHub · parents 48b0687, 56a7246 · Browse files · 3 files+28 added−1 removed
This commit

State

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

Diff stats

3 files+28 added−1 removed

  • tests:+19 added−0 removed
  • other:+9 added−1 removed

3 files+28 added−1 removed

modified:src/jinja2/compiler.py+6 added-1 removed
1139 unmodified lines
1140 f" getattr(included_template, {name!r}, missing)"1141 )1142 self.writeline(f"if {frame.symbols.ref(alias)} is missing:")1143 self.indent()1144 # The position will contain the template name, and will be formatted1145 # into a string that will be compiled into an f-string. Curly braces1146 # in the name must be replaced with escapes so that they will not be1147 # executed as part of the f-string.1148 position = self.position(node).replace("{", "{{").replace("}", "}}")1149 message = (1150 "the template {included_template.__name__!r}"1146 f" (imported on {self.position(node)})"1151 f" (imported on {position})"1152 f" does not export the requested name {name!r}"1153 )1154 self.writeline(1155 f"{frame.symbols.ref(alias)} = undefined(f{message!r}, name={name!r})"
826 unmodified lines
modified:tests/test_compile.py+19 added
1import os2import re34import pytest56from jinja2 import UndefinedError7from jinja2.environment import Environment8from jinja2.loaders import DictLoader910
78 unmodified lines
89 r"_block_vars\.update\(\{'a\d': l_0_a\d, 'b\d': l_0_b\d, 'c\d': l_0_c\d\}\)",90 content,91 )[:10]92 assert found == expect939495def test_undefined_import_curly_name():96 env = Environment(97 loader=DictLoader(98 {99 "{bad}": "{% from 'macro' import m %}{{ m() }}",100 "macro": "",101 }102 )103 )104105 # Must not raise `NameError: 'bad' is not defined`, as that would indicate106 # that `{bad}` is being interpreted as an f-string. It must be escaped.107 with pytest.raises(UndefinedError):108 env.get_template("{bad}").render()
modified:CHANGES.rst+3 added
6 unmodified lines
78- The sandboxed environment handles indirect calls to ``str.format``, such as9 by passing a stored reference to a filter that calls its argument.10 :ghsa:`q2x7-8rv6-6q7h`11- Escape template name before formatting it into error messages, to avoid12 issues with names that contain f-string syntax.13 :issue:`1792`, :ghsa:`gmj6-6f8f-6699`14- Sandbox does not allow ``clear`` and ``pop`` on known mutable sequence15 types. :issue:`2032`16- Calling sync ``render`` for an async template uses ``asyncio.run``.17 :pr:`1952`
1017 unmodified lines