Merge pull request #1233 from MLH-Fellowship/required-blocks
Before adoption: this commit came in with the history the project adopted, so no landing records it.
add required attribute to blocks
authored by Amy Lei · committed by GitHub · parents bc22a8b, 8da77f9 · 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
Provenance
- Commit
35e8f0a- Tree
d2fe10c- Author
Amy Lei <42757189+amy-lei@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
bc22a8b- Parent 2
8da77f9
7 files changed+183 added−4 removed
modified:docs/templates.rst+34 added
538 unmodified lines539 540 When overriding a block, the `scoped` modifier does not have to be provided.541 542 543+Required Blocks544+~~~~~~~~~~~~~~~~~~~~~~~545+546+Blocks can be marked as required. They must be overridden at some point,547+but not necessarily by the direct child template. Required blocks can548+only contain whitespace or comments, and they cannot be rendered directly.549+550+For example::551+552+ # parent.tmpl553+ body: {% block body required %}{% endblock %}554+555+ # child.tmpl556+ {% extends "parent.tmpl" %}557+558+ # grandchild.tmpl559+ {% extends "child.tmpl" %}560+ {% block body %}Hi from grandchild.{% endblock %}561+562+563+Rendering ``child.tmpl`` will give564+``TemplateRuntimeError``565+566+Rendering ``grandchild.tmpl`` will give567+``Hi from grandchild.``568+569+When combined with ``scoped``, the ``required`` modifier must be placed `after`570+the scoped modifier. Here are some valid examples::571+572+ {% block body scoped %}{% endblock %}573+ {% block body required %}{% endblock %}574+ {% block body scoped required %}{% endblock %}575+576+577 Template Objects578 ~~~~~~~~~~~~~~~~579 580 .. versionchanged:: 2.41282 unmodified linesmodified:src/jinja2/compiler.py+9 added
795 unmodified lines796 context = self.derive_context(frame)797 else:798 context = self.get_context_ref()799 800+ 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()808+809 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 linesmodified:src/jinja2/nodes.py+6 added-2 removed
338 unmodified lines339 fields = ("targets", "values", "body")340 341 342 class Block(Stmt):343- """A node that represents a block."""343+ """A node that represents a block.344 345- fields = ("name", "body", "scoped")345+ .. versionchanged:: 3.0.0346+ the `required` field was added.347+ """348 349+ fields = ("name", "body", "scoped", "required")350 351+352 class Include(Stmt):353 """A node that represents the include tag."""354 355 fields = ("template", "with_context", "ignore_missing")706 unmodified linesmodified:src/jinja2/parser.py+12 added-1 removed
253 unmodified lines254 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")259 260 # 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 lines266 " contain hyphens, use an underscore instead."267 )268 269 node.body = self.parse_statements(("name:endblock",), drop_needle=True)270+271+ # 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")280+281 self.stream.skip_if("name:" + node.name)282 return node283 284 def parse_extends(self):650 unmodified lines935 flush_data()936 finally:937 if end_tokens is not None:938 self._end_token_stack.pop()927-939 return body940 941 def parse(self):942 """Parse the whole template into a `Template` node."""3 unmodified linesmodified:tests/test_idtracking.py+2 added-1 removed
36 unmodified lines37 38 39 def 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 )43 44 render_title_macro = nodes.Macro(45 "render_title",90 unmodified lines136 for_loop,137 nodes.Output([nodes.TemplateData("\n </ul>\n")]),138 ],139 False,140+ False,141 )142 143 tmpl = nodes.Template(144 [146 unmodified linesmodified:tests/test_inheritance.py+118 added
1 unmodified line2 3 from jinja2 import DictLoader4 from jinja2 import Environment5 from jinja2 import TemplateRuntimeError6+from jinja2 import TemplateSyntaxError7 8 LAYOUTTEMPLATE = """\9 |{% block block1 %}block 1 from layout{% endblock %}10 |{% block block2 %}block 2 from layout{% endblock %}219 unmodified lines230 )231 rv = env.get_template("index.html").render(the_foo=42).split()232 assert rv == ["43", "44", "45"]233 234+ 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]"245 246+ 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()258+259+ assert rv1 == "[1]"260+ assert rv2 == "[2]"261+262+ 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")276+277+ with pytest.raises(TemplateRuntimeError, match="Required block 'x' not found"):278+ assert t1.render()279+280+ assert t2.render() == "[2]"281+ assert t3.render() == "[2]"282+283+ 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")299+300+ 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")307+308+ 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")325+326+ assert t1.render(seq=list(range(3))) == "[0][1][2]"327+328+ # scoped must come before required329+ with pytest.raises(TemplateSyntaxError):330+ t2.render(seq=list(range(3)))331+332+ 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)))350+351+352 class TestBugFix:353 def test_fixed_macro_scoping_bug(self, env):354 assert (355 Environment(47 unmodified linesmodified:CHANGES.rst+2 added
17 unmodified lines18 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`24 25 26 Version 2.11.227 --------------770 unmodified lines