Skip to content

Commit

Permalink
Make nested-trans-block exceptions nicer
Browse files Browse the repository at this point in the history
  • Loading branch information
akx committed Dec 15, 2023
1 parent d594969 commit 3b8f700
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
16 changes: 13 additions & 3 deletions src/jinja2/ext.py
Original file line number Diff line number Diff line change
Expand Up @@ -495,16 +495,26 @@ def _parse_block(
parser.stream.expect("variable_end")
elif parser.stream.current.type == "block_begin":
next(parser.stream)
if parser.stream.current.test("name:endtrans"):
block_name = (
parser.stream.current.value if
parser.stream.current.type == "name"
else None
)
if block_name == "endtrans":
break
elif parser.stream.current.test("name:pluralize"):
elif block_name == "pluralize":
if allow_pluralize:
break
parser.fail(
"a translatable section can have only one pluralize section"
)
elif block_name == "trans":
parser.fail(
f"trans blocks can't be nested; did you mean `endtrans`?"
)
parser.fail(
"control structures in translatable sections are not allowed"
f"control structures in translatable sections are not allowed; "
f"saw `{block_name}`"
)
elif parser.stream.eos:
parser.fail("unclosed translation block")
Expand Down
13 changes: 13 additions & 0 deletions tests/test_ext.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from jinja2 import DictLoader
from jinja2 import Environment
from jinja2 import TemplateSyntaxError
from jinja2 import nodes
from jinja2 import pass_context
from jinja2.exceptions import TemplateAssertionError
Expand Down Expand Up @@ -468,6 +469,18 @@ def test_extract_context(self):
(3, "npgettext", ("babel", "%(users)s user", "%(users)s users", None), []),
]

def test_nested_trans_error(self):
s = '{% trans %}foo{% trans %}{% endtrans %}'
with pytest.raises(TemplateSyntaxError) as excinfo:
i18n_env.from_string(s)
assert "trans blocks can't be nested" in str(excinfo.value)

def test_trans_block_error(self):
s = '{% trans %}foo{% wibble bar %}{% endwibble %}{% endtrans %}'
with pytest.raises(TemplateSyntaxError) as excinfo:
i18n_env.from_string(s)
assert "saw `wibble`" in str(excinfo.value)


class TestScope:
def test_basic_scope_behavior(self):
Expand Down

0 comments on commit 3b8f700

Please sign in to comment.