Skip to content

Commit

Permalink
Improve the PackageLoader error message (#1706)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidism authored Dec 20, 2024
2 parents 58a358f + aaa083d commit 53c7591
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 7 deletions.
2 changes: 2 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ Unreleased
- ``Environment.overlay(enable_async)`` is applied correctly. :pr:`2061`
- The error message from ``FileSystemLoader`` includes the paths that were
searched. :issue:`1661`
- ``PackageLoader`` shows a clearer error message when the package does not
contain the templates directory. :issue:`1705`


Version 3.1.4
Expand Down
18 changes: 11 additions & 7 deletions src/jinja2/loaders.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,6 @@ def __init__(
assert loader is not None, "A loader was not found for the package."
self._loader = loader
self._archive = None
template_root = None

if isinstance(loader, zipimport.zipimporter):
self._archive = loader.archive
Expand All @@ -344,18 +343,23 @@ def __init__(
elif spec.origin is not None:
roots.append(os.path.dirname(spec.origin))

if not roots:
raise ValueError(
f"The {package_name!r} package was not installed in a"
" way that PackageLoader understands."
)

for root in roots:
root = os.path.join(root, package_path)

if os.path.isdir(root):
template_root = root
break

if template_root is None:
raise ValueError(
f"The {package_name!r} package was not installed in a"
" way that PackageLoader understands."
)
else:
raise ValueError(
f"PackageLoader could not find a {package_path!r} directory"
f" in the {package_name!r} package."
)

self._template_root = template_root

Expand Down
5 changes: 5 additions & 0 deletions tests/test_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -429,3 +429,8 @@ def exec_module(self, module):
assert "test.html" in package_loader.list_templates()
finally:
sys.meta_path[:] = before


def test_package_loader_no_dir() -> None:
with pytest.raises(ValueError, match="could not find a 'templates' directory"):
PackageLoader("jinja2")

0 comments on commit 53c7591

Please sign in to comment.