Skip to content
Myr

add required attribute to blocks

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

required blocks must be overridden at some point, although not necessarily by the direct child template

authored by Amy · committed by Amy · parent bc22a8b · Browse files · 7 files+183 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

7 files+183 added−4 removed

  • tests:+120 added−1 removed
  • other:+63 added−3 removed

7 files+183 added−4 removed

modified:docs/templates.rst+34 added
538 unmodified lines
539540When overriding a block, the `scoped` modifier does not have to be provided.541542543Required Blocks544~~~~~~~~~~~~~~~~~~~~~~~545546Blocks can be marked as required. They must be overridden at some point,547but not necessarily by the direct child template. Required blocks can548only contain whitespace or comments, and they cannot be rendered directly.549550For example::551552 # parent.tmpl553 body: {% block body required %}{% endblock %}554555 # child.tmpl556 {% extends "parent.tmpl" %}557558 # grandchild.tmpl559 {% extends "child.tmpl" %}560 {% block body %}Hi from grandchild.{% endblock %}561562563Rendering ``child.tmpl`` will give564``TemplateRuntimeError``565566Rendering ``grandchild.tmpl`` will give567``Hi from grandchild.``568569When combined with ``scoped``, the ``required`` modifier must be placed `after`570the scoped modifier. Here are some valid examples::571572 {% block body scoped %}{% endblock %}573 {% block body required %}{% endblock %}574 {% block body scoped required %}{% endblock %}575576577Template Objects578~~~~~~~~~~~~~~~~579580.. versionchanged:: 2.4
1282 unmodified lines
modified:src/jinja2/compiler.py+9 added
795 unmodified lines
796 context = self.derive_context(frame)797 else:798 context = self.get_context_ref()799800 if node.required:801 self.writeline(f"if len(context.blocks[{node.name!r}]) <= 1:", node)802 self.indent()803 self.writeline(804 f'raise TemplateRuntimeError("Required block {node.name!r} not found")',805 node,806 )807 self.outdent()808809 if not self.environment.is_async and frame.buffer is None:810 self.writeline(811 f"yield from context.blocks[{node.name!r}][0]({context})", node812 )
951 unmodified lines
modified:src/jinja2/nodes.py+6 added-2 removed
338 unmodified lines
339 fields = ("targets", "values", "body")340341342class Block(Stmt):343 """A node that represents a block."""343 """A node that represents a block.344345 fields = ("name", "body", "scoped")345 .. versionchanged:: 3.0.0346 the `required` field was added.347 """348349 fields = ("name", "body", "scoped", "required")350351352class Include(Stmt):353 """A node that represents the include tag."""354355 fields = ("template", "with_context", "ignore_missing")
706 unmodified lines
modified:src/jinja2/parser.py+12 added-1 removed
253 unmodified lines
254 def parse_block(self):255 node = nodes.Block(lineno=next(self.stream).lineno)256 node.name = self.stream.expect("name").value257 node.scoped = self.stream.skip_if("name:scoped")258 node.required = self.stream.skip_if("name:required")259260 # common problem people encounter when switching from django261 # to jinja. we do not support hyphens in block names, so let's262 # raise a nicer error message in that case.
3 unmodified lines
266 " contain hyphens, use an underscore instead."267 )268269 node.body = self.parse_statements(("name:endblock",), drop_needle=True)270271 # enforce that required blocks only contain whitespace or comments272 # by asserting that the body, if not empty, is just TemplateData nodes273 # with whitespace data274 if node.required and not all(275 isinstance(child, nodes.TemplateData) and child.data.isspace()276 for body in node.body277 for child in body.nodes278 ):279 self.fail("Required blocks can only contain comments or whitespace")280281 self.stream.skip_if("name:" + node.name)282 return node283284 def parse_extends(self):
650 unmodified lines
935 flush_data()936 finally:937 if end_tokens is not None:938 self._end_token_stack.pop()927939 return body940941 def parse(self):942 """Parse the whole template into a `Template` node."""
3 unmodified lines
modified:tests/test_idtracking.py+2 added-1 removed
36 unmodified lines
373839def test_complex():40 title_block = nodes.Block(41 "title", [nodes.Output([nodes.TemplateData("Page Title")])], False41 "title", [nodes.Output([nodes.TemplateData("Page Title")])], False, False42 )4344 render_title_macro = nodes.Macro(45 "render_title",
90 unmodified lines
136 for_loop,137 nodes.Output([nodes.TemplateData("\n </ul>\n")]),138 ],139 False,140 False,141 )142143 tmpl = nodes.Template(144 [
146 unmodified lines
modified:tests/test_inheritance.py+118 added
1 unmodified line
23from jinja2 import DictLoader4from jinja2 import Environment5from jinja2 import TemplateRuntimeError6from jinja2 import TemplateSyntaxError78LAYOUTTEMPLATE = """\9|{% block block1 %}block 1 from layout{% endblock %}10|{% block block2 %}block 2 from layout{% endblock %}
219 unmodified lines
230 )231 rv = env.get_template("index.html").render(the_foo=42).split()232 assert rv == ["43", "44", "45"]233234 def test_level1_required(self, env):235 env = Environment(236 loader=DictLoader(237 {238 "master": "{% block x required %}{# comment #}\n {% endblock %}",239 "level1": "{% extends 'master' %}{% block x %}[1]{% endblock %}",240 }241 )242 )243 rv = env.get_template("level1").render()244 assert rv == "[1]"245246 def test_level2_required(self, env):247 env = Environment(248 loader=DictLoader(249 {250 "master": "{% block x required %}{% endblock %}",251 "level1": "{% extends 'master' %}{% block x %}[1]{% endblock %}",252 "level2": "{% extends 'master' %}{% block x %}[2]{% endblock %}",253 }254 )255 )256 rv1 = env.get_template("level1").render()257 rv2 = env.get_template("level2").render()258259 assert rv1 == "[1]"260 assert rv2 == "[2]"261262 def test_level3_required(self, env):263 env = Environment(264 loader=DictLoader(265 {266 "master": "{% block x required %}{% endblock %}",267 "level1": "{% extends 'master' %}",268 "level2": "{% extends 'level1' %}{% block x %}[2]{% endblock %}",269 "level3": "{% extends 'level2' %}",270 }271 )272 )273 t1 = env.get_template("level1")274 t2 = env.get_template("level2")275 t3 = env.get_template("level3")276277 with pytest.raises(TemplateRuntimeError, match="Required block 'x' not found"):278 assert t1.render()279280 assert t2.render() == "[2]"281 assert t3.render() == "[2]"282283 def test_invalid_required(self, env):284 env = Environment(285 loader=DictLoader(286 {287 "master": "{% block x required %}data {# #}{% endblock %}",288 "master1": "{% block x required %}{% block y %}"289 "{% endblock %} {% endblock %}",290 "master2": "{% block x required %}{% if true %}"291 "{% endif %} {% endblock %}",292 "level1": "{% if master %}{% extends master %}"293 "{% else %}{% extends 'master' %}{% endif %}"294 "{%- block x %}CHILD{% endblock %}",295 }296 )297 )298 t = env.get_template("level1")299300 with pytest.raises(301 TemplateSyntaxError,302 match="Required blocks can only contain comments or whitespace",303 ):304 assert t.render(master="master")305 assert t.render(master="master2")306 assert t.render(master="master3")307308 def test_required_with_scope(self, env):309 env = Environment(310 loader=DictLoader(311 {312 "master1": "{% for item in seq %}[{% block item scoped required %}"313 "{% endblock %}]{% endfor %}",314 "child1": "{% extends 'master1' %}{% block item %}"315 "{{ item }}{% endblock %}",316 "master2": "{% for item in seq %}[{% block item required scoped %}"317 "{% endblock %}]{% endfor %}",318 "child2": "{% extends 'master2' %}{% block item %}"319 "{{ item }}{% endblock %}",320 }321 )322 )323 t1 = env.get_template("child1")324 t2 = env.get_template("child2")325326 assert t1.render(seq=list(range(3))) == "[0][1][2]"327328 # scoped must come before required329 with pytest.raises(TemplateSyntaxError):330 t2.render(seq=list(range(3)))331332 def test_duplicate_required_or_scoped(self, env):333 env = Environment(334 loader=DictLoader(335 {336 "master1": "{% for item in seq %}[{% block item "337 "scoped scoped %}}{{% endblock %}}]{{% endfor %}}",338 "master2": "{% for item in seq %}[{% block item "339 "required required %}}{{% endblock %}}]{{% endfor %}}",340 "child": "{% if master %}{% extends master %}{% else %}"341 "{% extends 'master1' %}{% endif %}{%- block x %}"342 "CHILD{% endblock %}",343 }344 )345 )346 tmpl = env.get_template("child")347 with pytest.raises(TemplateSyntaxError):348 tmpl.render(master="master1", seq=list(range(3)))349 tmpl.render(master="master2", seq=list(range(3)))350351352class TestBugFix:353 def test_fixed_macro_scoping_bug(self, env):354 assert (355 Environment(
47 unmodified lines
modified:CHANGES.rst+2 added
17 unmodified lines
18 constant input. :issue:`1279`19- Fix UndefinedError incorrectly being thrown on an undefined variable20 instead of ``Undefined`` being returned on21 ``NativeEnvironment`` on Python 3.10. :issue:`1335`22- Add ``required`` attribute to blocks that must be overridden at some23 point, but not necessarily by the direct child :issue:`1147`242526Version 2.11.227--------------
770 unmodified lines