Merge pull request #1080 from pallets/no-finalize-template-data
Before adoption: this commit came in with the history the project adopted, so no landing records it.
don't finalize TemplateData nodes
authored by David Lord · committed by GitHub · parents 636c712, 719537a · Browse files · 4 files·+88 added−40 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+88 added−40 removed
- tests:+47 added−10 removed
- other:+41 added−30 removed
Provenance
- Commit
0687adf- Tree
6ae8ae0- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
636c712- Parent 2
719537a
4 files changed+88 added−40 removed
modified:jinja2/compiler.py+37 added-30 removed
1222 unmodified lines1223 # if we are in a require_output_check section1224 if self.has_known_extends and frame.require_output_check:1225 return1226 1227+ finalize = text_type1228+ finalize_src = None1229 allow_constant_finalize = True1230+1231 if self.environment.finalize:1229- func = self.environment.finalize1230- if getattr(func, 'contextfunction', False) or \1231- getattr(func, 'evalcontextfunction', False):1232+ env_finalize = self.environment.finalize1233+ finalize_src = "environment.finalize("1234+1235+ def finalize(value):1236+ return text_type(env_finalize(value))1237+1238+ if getattr(env_finalize, "contextfunction", False):1239+ finalize_src += "context, "1240 allow_constant_finalize = False1233- elif getattr(func, 'environmentfunction', False):1234- finalize = lambda x: text_type(1235- self.environment.finalize(self.environment, x))1236- else:1237- finalize = lambda x: text_type(self.environment.finalize(x))1238- else:1239- finalize = text_type1241+ elif getattr(env_finalize, "evalcontextfunction", False):1242+ finalize_src += "context.eval_ctx, "1243+ allow_constant_finalize = False1244+ elif getattr(env_finalize, "environmentfunction", False):1245+ finalize_src += "environment, "1246 1247+ def finalize(value):1248+ return text_type(env_finalize(self.environment, value))1249+1250 # if we are inside a frame that requires output checking, we do so1251 outdent_later = False1252 if frame.require_output_check:1253 self.writeline('if parent_template is None:')4 unmodified lines1258 # string at compile time.1259 body = []1260 for child in node.nodes:1261 try:1253- if not allow_constant_finalize:1262+ # If the finalize function needs context, and this isn't1263+ # template data, evaluate the node at render.1264+ if not (1265+ allow_constant_finalize1266+ or isinstance(child, nodes.TemplateData)1267+ ):1268 raise nodes.Impossible()1269+1270 const = child.as_const(frame.eval_ctx)1271 except nodes.Impossible:1272 body.append(child)1273 continue1274+1275 # the frame can't be volatile here, becaus otherwise the1276 # as_const() function would raise an Impossible exception1277 # at that point.1278 try:1279 if frame.eval_ctx.autoescape:1264- if hasattr(const, '__html__'):1265- const = const.__html__()1266- else:1267- const = escape(const)1268- const = finalize(const)1280+ const = escape(const)1281+1282+ # Only call finalize on expressions, not template data.1283+ if isinstance(child, nodes.TemplateData):1284+ const = text_type(const)1285+ else:1286+ const = finalize(const)1287 except Exception:1288 # if something goes wrong here we evaluate the node1289 # at runtime for easier debugging1290 body.append(child)1291 continue1292+1293 if body and isinstance(body[-1], list):1294 body[-1].append(const)1295 else:1296 body.append([const])27 unmodified lines1324 self.write('escape(')1325 else:1326 self.write('to_string(')1327 if self.environment.finalize is not None:1309- self.write('environment.finalize(')1310- if getattr(self.environment.finalize,1311- "contextfunction", False):1312- self.write('context, ')1328+ self.write(finalize_src)1329 close += 11330 self.visit(item, frame)1331 self.write(')' * close)1332 if frame.buffer is not None:26 unmodified lines1359 elif frame.eval_ctx.autoescape:1360 self.write('escape(')1361 close += 11362 if self.environment.finalize is not None:1347- self.write('environment.finalize(')1348- if getattr(self.environment.finalize,1349- 'contextfunction', False):1350- self.write('context, ')1351- elif getattr(self.environment.finalize,1352- 'evalcontextfunction', False):1353- self.write('context.eval_ctx, ')1354- elif getattr(self.environment.finalize,1355- 'environmentfunction', False):1356- self.write('environment, ')1363+ self.write(finalize_src)1364 close += 11365 self.visit(argument, frame)1366 self.write(')' * close + ', ')1367 self.outdent()363 unmodified linesmodified:tests/test_api.py+47 added-10 removed
17 unmodified lines18 is_undefined, Template, DictLoader, make_logging_undefined19 from jinja2.compiler import CodeGenerator20 from jinja2.runtime import Context21 from jinja2.utils import Cycler22+from jinja2.utils import contextfunction23+from jinja2.utils import evalcontextfunction24+from jinja2.utils import environmentfunction25 26 27 @pytest.mark.api28 @pytest.mark.extended10 unmodified lines39 assert tmpl.render(foo={'items': 42}) == "[('items', 42)]"40 tmpl = env.from_string('{{ foo["items"] }}')41 assert tmpl.render(foo={'items': 42}) == '42'42 40- def test_finalizer(self, env):41- def finalize_none_empty(value):42- if value is None:43- value = u''44- return value45- env = Environment(finalize=finalize_none_empty)46- tmpl = env.from_string('{% for item in seq %}|{{ item }}{% endfor %}')47- assert tmpl.render(seq=(None, 1, "foo")) == '||1|foo'48- tmpl = env.from_string('<{{ none }}>')49- assert tmpl.render() == '<>'43+ def test_finalize(self):44+ e = Environment(finalize=lambda v: "" if v is None else v)45+ t = e.from_string("{% for item in seq %}|{{ item }}{% endfor %}")46+ assert t.render(seq=(None, 1, "foo")) == "||1|foo"47 48+ def test_finalize_constant_expression(self):49+ e = Environment(finalize=lambda v: "" if v is None else v)50+ t = e.from_string("<{{ none }}>")51+ assert t.render() == "<>"52+53+ def test_no_finalize_template_data(self):54+ e = Environment(finalize=lambda v: type(v).__name__)55+ t = e.from_string("<{{ value }}>")56+ # If template data was finalized, it would print "strintstr".57+ assert t.render(value=123) == "<int>"58+59+ def test_context_finalize(self):60+ @contextfunction61+ def finalize(context, value):62+ return value * context["scale"]63+64+ e = Environment(finalize=finalize)65+ t = e.from_string("{{ value }}")66+ assert t.render(value=5, scale=3) == "15"67+68+ def test_eval_finalize(self):69+ @evalcontextfunction70+ def finalize(eval_ctx, value):71+ return str(eval_ctx.autoescape) + value72+73+ e = Environment(finalize=finalize, autoescape=True)74+ t = e.from_string("{{ value }}")75+ assert t.render(value="<script>") == "True<script>"76+77+ def test_env_autoescape(self):78+ @environmentfunction79+ def finalize(env, value):80+ return " ".join(81+ (env.variable_start_string, repr(value), env.variable_end_string)82+ )83+84+ e = Environment(finalize=finalize)85+ t = e.from_string("{{ value }}")86+ assert t.render(value="hello") == "{{ 'hello' }}"87+88 def test_cycler(self, env):89 items = 1, 2, 390 c = Cycler(*items)91 for item in items + items:323 unmodified linesmodified:.gitignore+1 added
15 unmodified lines16 .coverage17 .coverage.*18 htmlcov19 .pytest_cache/20+/.vscode/modified:CHANGES.rst+3 added
32 unmodified lines33 ``{{ 2 * (3 < 5) }}`` outputs "2" instead of "False".34 :issue:`755`, :pr:`938`35 - Add new ``boolean``, ``false``, ``true``, ``integer`` and ``float``36 tests. :pr:`824`37+- The environment's ``finalize`` function is only applied to the38+ output of expressions (constant or not), not static template data.39+ :issue:`63`40 41 42 Version 2.10.343 --------------629 unmodified lines