Skip to content

Commit

Permalink
Fixed #35789 -- Improved the error message raised when the tag must b…
Browse files Browse the repository at this point in the history
…e first in the template.
  • Loading branch information
ekinertac authored and sarahboyce committed Oct 10, 2024
1 parent e970bb7 commit 68cee15
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
6 changes: 5 additions & 1 deletion django/template/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -533,9 +533,13 @@ def skip_past(self, endtag):
def extend_nodelist(self, nodelist, node, token):
# Check that non-text nodes don't appear before an extends tag.
if node.must_be_first and nodelist.contains_nontext:
if self.origin.template_name:
origin = repr(self.origin.template_name)
else:
origin = "the template"
raise self.error(
token,
"%r must be the first tag in the template." % node,
"{%% %s %%} must be the first tag in %s." % (token.contents, origin),
)
if not isinstance(node, TextNode):
nodelist.contains_nontext = True
Expand Down
18 changes: 16 additions & 2 deletions tests/template_tests/test_extends.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import os

from django.template import Context, Engine, TemplateDoesNotExist
from django.template import Context, Engine, TemplateDoesNotExist, TemplateSyntaxError
from django.test import SimpleTestCase

from .utils import ROOT
from .utils import ROOT, setup

RECURSIVE = os.path.join(ROOT, "recursive_templates")

Expand Down Expand Up @@ -181,3 +181,17 @@ def test_block_override_in_extended_included_template(self):
)
template = engine.get_template("base.html")
self.assertEqual(template.render(Context({})), "12AB")

@setup(
{"index.html": "{% block content %}B{% endblock %}{% extends 'base.html' %}"}
)
def test_extends_not_first_tag_in_extended_template(self):
msg = "{% extends 'base.html' %} must be the first tag in 'index.html'."
with self.assertRaisesMessage(TemplateSyntaxError, msg):
self.engine.get_template("index.html")

def test_extends_not_first_tag_in_extended_template_from_string(self):
template_string = "{% block content %}B{% endblock %}{% extends 'base.html' %}"
msg = "{% extends 'base.html' %} must be the first tag in the template."
with self.assertRaisesMessage(TemplateSyntaxError, msg):
Engine().from_string(template_string)

0 comments on commit 68cee15

Please sign in to comment.