Skip to content

Commit 19a55db

Browse files
akxdavidism
authored andcommitted
Make nested-trans-block exceptions nicer
1 parent 7167953 commit 19a55db

File tree

3 files changed

+28
-3
lines changed

3 files changed

+28
-3
lines changed

CHANGES.rst

+2
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ Unreleased
88
- Fix compiler error when checking if required blocks in parent templates are
99
empty. :pr:`1858`
1010
- ``xmlattr`` filter does not allow keys with spaces. GHSA-h5c8-rqwp-cp95
11+
- Make error messages stemming from invalid nesting of ``{% trans %}`` blocks
12+
more helpful. :pr:`1916`
1113

1214

1315
Version 3.1.2

src/jinja2/ext.py

+13-3
Original file line numberDiff line numberDiff line change
@@ -495,16 +495,26 @@ def _parse_block(
495495
parser.stream.expect("variable_end")
496496
elif parser.stream.current.type == "block_begin":
497497
next(parser.stream)
498-
if parser.stream.current.test("name:endtrans"):
498+
block_name = (
499+
parser.stream.current.value
500+
if parser.stream.current.type == "name"
501+
else None
502+
)
503+
if block_name == "endtrans":
499504
break
500-
elif parser.stream.current.test("name:pluralize"):
505+
elif block_name == "pluralize":
501506
if allow_pluralize:
502507
break
503508
parser.fail(
504509
"a translatable section can have only one pluralize section"
505510
)
511+
elif block_name == "trans":
512+
parser.fail(
513+
"trans blocks can't be nested; did you mean `endtrans`?"
514+
)
506515
parser.fail(
507-
"control structures in translatable sections are not allowed"
516+
f"control structures in translatable sections are not allowed; "
517+
f"saw `{block_name}`"
508518
)
509519
elif parser.stream.eos:
510520
parser.fail("unclosed translation block")

tests/test_ext.py

+13
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from jinja2 import Environment
88
from jinja2 import nodes
99
from jinja2 import pass_context
10+
from jinja2 import TemplateSyntaxError
1011
from jinja2.exceptions import TemplateAssertionError
1112
from jinja2.ext import Extension
1213
from jinja2.lexer import count_newlines
@@ -468,6 +469,18 @@ def test_extract_context(self):
468469
(3, "npgettext", ("babel", "%(users)s user", "%(users)s users", None), []),
469470
]
470471

472+
def test_nested_trans_error(self):
473+
s = "{% trans %}foo{% trans %}{% endtrans %}"
474+
with pytest.raises(TemplateSyntaxError) as excinfo:
475+
i18n_env.from_string(s)
476+
assert "trans blocks can't be nested" in str(excinfo.value)
477+
478+
def test_trans_block_error(self):
479+
s = "{% trans %}foo{% wibble bar %}{% endwibble %}{% endtrans %}"
480+
with pytest.raises(TemplateSyntaxError) as excinfo:
481+
i18n_env.from_string(s)
482+
assert "saw `wibble`" in str(excinfo.value)
483+
471484

472485
class TestScope:
473486
def test_basic_scope_behavior(self):

0 commit comments

Comments
 (0)