Skip to content
Myr

xmlattr filter disallows keys with spaces

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

authored by Calum Hutton · committed by David Lord · parent d84a174 · Browse files · 3 files+28 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

3 files+28 added−7 removed

  • tests:+6 added−0 removed
  • other:+22 added−7 removed

3 files+28 added−7 removed

modified:src/jinja2/filters.py+21 added-7 removed
246 unmodified lines
247248 yield from value.items()249250251_space_re = re.compile(r"\s", flags=re.ASCII)252253254@pass_eval_context255def do_xmlattr(256 eval_ctx: "EvalContext", d: t.Mapping[str, t.Any], autospace: bool = True257) -> str:258 """Create an SGML/XML attribute string based on the items in a dict.256 All values that are neither `none` nor `undefined` are automatically257 escaped:259260 If any key contains a space, this fails with a ``ValueError``. Values that261 are neither ``none`` nor ``undefined`` are automatically escaped.262263 .. sourcecode:: html+jinja264265 <ul{{ {'class': 'my_list', 'missing': none,266 'id': 'list-%d'|format(variable)}|xmlattr }}>
9 unmodified lines
276 </ul>277278 As you can see it automatically prepends a space in front of the item279 if the filter returned something unless the second parameter is false.280281 .. versionchanged:: 3.1.3282 Keys with spaces are not allowed.283 """277 rv = " ".join(278 f'{escape(key)}="{escape(value)}"'279 for key, value in d.items()280 if value is not None and not isinstance(value, Undefined)281 )284 items = []285286 for key, value in d.items():287 if value is None or isinstance(value, Undefined):288 continue289290 if _space_re.search(key) is not None:291 raise ValueError(f"Spaces are not allowed in attributes: '{key}'")292293 items.append(f'{escape(key)}="{escape(value)}"')294295 rv = " ".join(items)296297 if autospace and rv:298 rv = " " + rv299300 if eval_ctx.autoescape:
1554 unmodified lines
modified:tests/test_filters.py+6 added
472 unmodified lines
473 assert 'foo="42"' in out474 assert 'bar="23"' in out475 assert 'blub:blub="&lt;?&gt;"' in out476477 def test_xmlattr_key_with_spaces(self, env):478 with pytest.raises(ValueError, match="Spaces are not allowed"):479 env.from_string(480 "{{ {'src=1 onerror=alert(1)': 'my_class'}|xmlattr }}"481 ).render()482483 def test_sort1(self, env):484 tmpl = env.from_string("{{ [2, 3, 1]|sort }}|{{ [2, 3, 1]|sort(true) }}")485 assert tmpl.render() == "[1, 2, 3]|[3, 2, 1]"486
395 unmodified lines
modified:CHANGES.rst+1 added
5 unmodified lines
6Unreleased78- Fix compiler error when checking if required blocks in parent templates are9 empty. :pr:`1858`10- ``xmlattr`` filter does not allow keys with spaces. GHSA-h5c8-rqwp-cp95111213Version 3.1.214-------------
971 unmodified lines