Skip to content

Commit eec0db8

Browse files
committed
PackageLoader works with single module file
1 parent 46f3a68 commit eec0db8

File tree

3 files changed

+36
-4
lines changed

3 files changed

+36
-4
lines changed

CHANGES.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ Unreleased
1313
:issue:`1514`
1414
- Revert change to ``hash(Node)`` behavior. Nodes are hashed by id
1515
again :issue:`1521`
16+
- ``PackageLoader`` works when the package is a single module file.
17+
:issue:`1512`
1618

1719

1820
Version 3.0.2

src/jinja2/loaders.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -297,10 +297,18 @@ def __init__(
297297
self._archive = loader.archive
298298
pkgdir = next(iter(spec.submodule_search_locations)) # type: ignore
299299
template_root = os.path.join(pkgdir, package_path)
300-
elif spec.submodule_search_locations:
301-
# This will be one element for regular packages and multiple
302-
# for namespace packages.
303-
for root in spec.submodule_search_locations:
300+
else:
301+
roots: t.List[str] = []
302+
303+
# One element for regular packages, multiple for namespace
304+
# packages, or None for single module file.
305+
if spec.submodule_search_locations:
306+
roots.extend(spec.submodule_search_locations)
307+
# A single module file, use the parent directory instead.
308+
elif spec.origin is not None:
309+
roots.append(os.path.dirname(spec.origin))
310+
311+
for root in roots:
304312
root = os.path.join(root, package_path)
305313

306314
if os.path.isdir(root):

tests/test_loader.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,28 @@ def test_package_dir_list(package_dir_loader):
313313
assert "test.html" in templates
314314

315315

316+
@pytest.fixture()
317+
def package_file_loader(monkeypatch):
318+
monkeypatch.syspath_prepend(Path(__file__).parent / "res")
319+
return PackageLoader("__init__")
320+
321+
322+
@pytest.mark.parametrize(
323+
("template", "expect"), [("foo/test.html", "FOO"), ("test.html", "BAR")]
324+
)
325+
def test_package_file_source(package_file_loader, template, expect):
326+
source, name, up_to_date = package_file_loader.get_source(None, template)
327+
assert source.rstrip() == expect
328+
assert name.endswith(os.path.join(*split_template_path(template)))
329+
assert up_to_date()
330+
331+
332+
def test_package_file_list(package_file_loader):
333+
templates = package_file_loader.list_templates()
334+
assert "foo/test.html" in templates
335+
assert "test.html" in templates
336+
337+
316338
@pytest.fixture()
317339
def package_zip_loader(monkeypatch):
318340
package_zip = (Path(__file__) / ".." / "res" / "package.zip").resolve()

0 commit comments

Comments
 (0)