Skip to content

Commit

Permalink
fixes #129 for jinja backend
Browse files Browse the repository at this point in the history
  • Loading branch information
bckohan committed Nov 20, 2023
1 parent f6b7b08 commit 5b379fa
Show file tree
Hide file tree
Showing 11 changed files with 135 additions and 36 deletions.
2 changes: 1 addition & 1 deletion render_static/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,6 @@ def select_templates(
loader specific and documented on the loader.
:return: The list of resolved template names
"""

template_names = set()
if callable(getattr(self.env.loader, 'select_templates', None)):
for templates in self.env.loader.select_templates(selector):
Expand All @@ -223,6 +222,7 @@ def select_templates(
else:
self.get_template(selector)
template_names.add(selector)

if first_loader and template_names:
return list(template_names)

Expand Down
4 changes: 2 additions & 2 deletions render_static/loaders/django.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
Templates in the future.
"""

from collections.abc import Container
from glob import glob
from os.path import relpath
from pathlib import Path
from collections.abc import Container
from typing import Generator, List, Tuple, Union, Optional
from typing import Generator, List, Optional, Tuple, Union

from django.apps import apps
from django.apps.config import AppConfig
Expand Down
62 changes: 59 additions & 3 deletions render_static/loaders/jinja2.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,22 @@
https://jinja.palletsprojects.com/en/3.0.x/api/#loaders
"""
from os.path import normpath
from pathlib import Path
from typing import (
TYPE_CHECKING,
Any,
Callable,
MutableMapping,
Optional,
Tuple,
)

from render_static import Jinja2DependencyNeeded
from render_static.loaders.mixins import BatchLoaderMixin

try:
from jinja2.exceptions import TemplateNotFound
from jinja2.loaders import (
ChoiceLoader,
DictLoader,
Expand All @@ -20,6 +32,9 @@
PackageLoader,
PrefixLoader,
)
if TYPE_CHECKING:
from jinja2 import Environment, Template # pragma: no cover

except ImportError: # pragma: no cover
ChoiceLoader = Jinja2DependencyNeeded # type: ignore
DictLoader = Jinja2DependencyNeeded # type: ignore
Expand All @@ -44,10 +59,51 @@
class StaticFileSystemLoader(FileSystemLoader): # pylint: disable=R0903
"""
https://jinja.palletsprojects.com/en/3.0.x/api/#jinja2.FileSystemLoader
"""

class StaticFileSystemBatchLoader(FileSystemLoader, BatchLoaderMixin):
We adapt the base loader to support loading directories as templates.
"""
is_dir: bool = False

def load(
self,
environment: "Environment",
name: str,
globals: Optional[ # pylint: disable=redefined-builtin
MutableMapping[str, Any]
] = None,
) -> "Template":
"""
Wrap load so we can tag directory templates with is_dir.
"""
tmpl = super().load(environment, name, globals)
setattr(tmpl, 'is_dir', self.is_dir)
return tmpl

def get_source(
self, environment: "Environment", template: str
) -> Tuple[str, str, Callable[[], bool]]:
"""
Wrap get_source and handle the case where the template is
a directory.
"""
try:
self.is_dir = False
return super().get_source(environment, template)
except TemplateNotFound:
for search_path in self.searchpath:
pth = Path(search_path) / template
if pth.is_dir():
self.is_dir = True
# code cov bug here, ignore it
return ( # pragma: no cover
'',
normpath(pth),
lambda: True
)
raise


class StaticFileSystemBatchLoader(StaticFileSystemLoader, BatchLoaderMixin):
"""
This loader extends the basic StaticFileSystemLoader to work with batch
selectors. Use this loader if you want to be able to use wildcards to load
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{{ variable }}
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{{ variable1 }}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{{ variable2 }}
Empty file.
34 changes: 34 additions & 0 deletions render_static/tests/jinja2_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,13 @@
from render_static.tests.tests import (
APP1_STATIC_DIR,
APP2_STATIC_DIR,
BATCH_RENDER_TEMPLATES,
EXPECTED_DIR,
GLOBAL_STATIC_DIR,
STATIC_TEMP_DIR,
STATIC_TEMP_DIR2,
BaseTestCase,
BatchRenderTestCase,
TemplatePreferenceFSTestCase,
empty_or_dne,
generate_context1,
Expand Down Expand Up @@ -624,3 +626,35 @@ def test_wildcards2(self):
),
]:
self.assertTrue(filecmp.cmp(source, dest, shallow=False))


@override_settings(STATIC_TEMPLATES={
'ENGINES': [{
'BACKEND': 'render_static.backends.StaticJinja2Templates',
'APP_DIRS': True,
'OPTIONS': {
'autoescape': False
}
}],
'templates': BATCH_RENDER_TEMPLATES
})
class Jinja2BatchRenderTestCase(BatchRenderTestCase):

def tearDown(self):
pass

@override_settings(STATIC_TEMPLATES={
'ENGINES': [{
'BACKEND': 'render_static.backends.StaticJinja2Templates',
'APP_DIRS': True,
'OPTIONS': {
'autoescape': False
}
}],
'templates': [
('batch_test/{{ dne }}', {})
]
})
def test_batch_render_not_found(self):
with self.assertRaises(CommandError):
call_command('renderstatic', 'batch_test/{{ dne }}')
61 changes: 31 additions & 30 deletions render_static/tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -1358,35 +1358,36 @@ def transpiler1(): # pragma: no cover
pass # pragma: no cover


BATCH_RENDER_TEMPLATES = [
(
'batch_test/**/*',
{
'context': {
'site_name': 'my_site',
'variable1': 'var1 value',
'variable2': 2,
'sub_dir': 'resources'
},
'dest': GLOBAL_STATIC_DIR
}
),
(
'batch_test/{{ site_name }}',
{
'context': {'site_name': 'my_site'},
'dest': GLOBAL_STATIC_DIR / 'batch_test' / '{{ site_name }}'
}
),
(
'batch_test/{{ site_name }}/{{ sub_dir }}',
{
'context': {'site_name': 'my_site', 'sub_dir': 'resources'},
'dest': GLOBAL_STATIC_DIR / 'batch_test' / '{{ site_name }}' / '{{ sub_dir }}'
}
)
]
@override_settings(STATIC_TEMPLATES={
'templates': [
(
'batch_test/**/*',
{
'context': {
'site_name': 'my_site',
'variable1': 'var1 value',
'variable2': 2,
'sub_dir': 'resources'
},
'dest': GLOBAL_STATIC_DIR
}
),
(
'batch_test/{{ site_name }}',
{
'context': {'site_name': 'my_site'},
'dest': GLOBAL_STATIC_DIR / 'batch_test' / '{{ site_name }}'
}
),
(
'batch_test/{{ site_name }}/{{ sub_dir }}',
{
'context': {'site_name': 'my_site', 'sub_dir': 'resources'},
'dest': GLOBAL_STATIC_DIR / 'batch_test' / '{{ site_name }}' / '{{ sub_dir }}'
}
)
]
'templates': BATCH_RENDER_TEMPLATES
})
class BatchRenderTestCase(BaseTestCase):
"""
Expand Down Expand Up @@ -1427,8 +1428,8 @@ def test_batch_render_path_templates(self):
self.assertTrue(file1.is_file())
self.assertTrue(file2.is_file())

self.assertEqual(file1.read_text(), 'var1 value\n')
self.assertEqual(file2.read_text(), '2\n')
self.assertEqual(file1.read_text().strip(), 'var1 value')
self.assertEqual(file2.read_text().strip(), '2')

# def tearDown(self):
# pass
5 changes: 5 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ addopts =
#log_cli = true
#log_cli_level = INFO

[coverage:run]
# dont exempt tests from coverage - useful to make sure they're being run
omit =
render_static/tests/app1/static_jinja2/batch_test/**/*

[mypy]
# The mypy configurations: http://bit.ly/2zEl9WI
allow_redefinition = False
Expand Down

0 comments on commit 5b379fa

Please sign in to comment.