Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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")
Loading