Skip to content
Myr

don't finalize TemplateData nodes

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

Finalize only applies to the output of expressions (constant or not). Add tests for context, eval, and env finalize functions.

authored by David Lord · committed by David Lord · parent 636c712 · 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

4 files+88 added−40 removed

modified:jinja2/compiler.py+37 added-30 removed
1222 unmodified lines
1223 # if we are in a require_output_check section1224 if self.has_known_extends and frame.require_output_check:1225 return12261227 finalize = text_type1228 finalize_src = None1229 allow_constant_finalize = True12301231 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("12341235 def finalize(value):1236 return text_type(env_finalize(value))12371238 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, "12461247 def finalize(value):1248 return text_type(env_finalize(self.environment, value))12491250 # 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 lines
1258 # 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()12691270 const = child.as_const(frame.eval_ctx)1271 except nodes.Impossible:1272 body.append(child)1273 continue12741275 # 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)12811282 # 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 continue12921293 if body and isinstance(body[-1], list):1294 body[-1].append(const)1295 else:1296 body.append([const])
27 unmodified lines
1324 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 lines
1359 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 lines
modified:tests/test_api.py+47 added-10 removed
17 unmodified lines
18 is_undefined, Template, DictLoader, make_logging_undefined19from jinja2.compiler import CodeGenerator20from jinja2.runtime import Context21from jinja2.utils import Cycler22from jinja2.utils import contextfunction23from jinja2.utils import evalcontextfunction24from jinja2.utils import environmentfunction252627@pytest.mark.api28@pytest.mark.extended
10 unmodified lines
39 assert tmpl.render(foo={'items': 42}) == "[('items', 42)]"40 tmpl = env.from_string('{{ foo["items"] }}')41 assert tmpl.render(foo={'items': 42}) == '42'4240 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"4748 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() == "<>"5253 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>"5859 def test_context_finalize(self):60 @contextfunction61 def finalize(context, value):62 return value * context["scale"]6364 e = Environment(finalize=finalize)65 t = e.from_string("{{ value }}")66 assert t.render(value=5, scale=3) == "15"6768 def test_eval_finalize(self):69 @evalcontextfunction70 def finalize(eval_ctx, value):71 return str(eval_ctx.autoescape) + value7273 e = Environment(finalize=finalize, autoescape=True)74 t = e.from_string("{{ value }}")75 assert t.render(value="<script>") == "True&lt;script&gt;"7677 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 )8384 e = Environment(finalize=finalize)85 t = e.from_string("{{ value }}")86 assert t.render(value="hello") == "{{ 'hello' }}"8788 def test_cycler(self, env):89 items = 1, 2, 390 c = Cycler(*items)91 for item in items + items:
323 unmodified lines
modified:.gitignore+1 added
15 unmodified lines
16.coverage17.coverage.*18htmlcov19.pytest_cache/20/.vscode/
modified:CHANGES.rst+3 added
32 unmodified lines
33 ``{{ 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`404142Version 2.10.343--------------
629 unmodified lines