Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make attributes set by the user propagate to all assets #142

Merged
merged 4 commits into from
Sep 16, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
18 changes: 10 additions & 8 deletions django_vite/core/asset_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ def generate_vite_asset(
scripts_attrs = {"type": "module", "crossorigin": "", **kwargs}

# Add dependent CSS
tags.extend(self._load_css_files_of_asset(path))
tags.extend(self._load_css_files_of_asset(path, attrs=kwargs))

# Add the script by itself
url = self._get_production_server_url(manifest_entry.file)
Expand All @@ -330,6 +330,7 @@ def generate_vite_asset(
"crossorigin": "anonymous",
"rel": "modulepreload",
"as": "script",
**kwargs,
}

for dep in manifest_entry.imports:
Expand Down Expand Up @@ -390,7 +391,7 @@ def preload_vite_asset(
)

# Add dependent CSS
tags.extend(self._preload_css_files_of_asset(path))
tags.extend(self._preload_css_files_of_asset(path, attrs=None))

# Preload imports
for dep in manifest_entry.imports:
Expand All @@ -407,21 +408,21 @@ def preload_vite_asset(
return "\n".join(tags)

def _preload_css_files_of_asset(
self,
path: str,
self, path: str, attrs: Optional[Dict[str, str]] = None
) -> List[Tag]:
return self._generate_css_files_of_asset(
path,
tag_generator=TagGenerator.stylesheet_preload,
attrs=attrs,
).tags

def _load_css_files_of_asset(
self,
path: str,
self, path: str, attrs: Optional[Dict[str, str]] = None
) -> List[Tag]:
return self._generate_css_files_of_asset(
path,
tag_generator=TagGenerator.stylesheet,
attrs=attrs,
).tags

class GeneratedCssFilesOutput(NamedTuple):
Expand All @@ -435,6 +436,7 @@ def _generate_css_files_of_asset(
path: str,
already_processed: Optional[List[str]] = None,
tag_generator: Callable[[str], Tag] = TagGenerator.stylesheet,
attrs: Optional[Dict[str, str]] = None,
) -> GeneratedCssFilesOutput:
"""
Generates all CSS tags for dependencies of an asset.
Expand All @@ -455,14 +457,14 @@ def _generate_css_files_of_asset(

for import_path in manifest_entry.imports:
new_tags, _ = self._generate_css_files_of_asset(
import_path, already_processed, tag_generator
import_path, already_processed, tag_generator, attrs
)
tags.extend(new_tags)

for css_path in manifest_entry.css:
if css_path not in already_processed:
url = self._get_production_server_url(css_path)
tags.append(tag_generator(url))
tags.append(tag_generator(url, attrs=attrs))
already_processed.append(css_path)

return self.GeneratedCssFilesOutput(tags, already_processed)
Expand Down
14 changes: 9 additions & 5 deletions django_vite/core/tag_generator.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Dict
from typing import Dict, Optional

Tag = str

Expand Down Expand Up @@ -36,7 +36,7 @@ def script(src: str, attrs: Dict[str, str]) -> Tag:
return f'<script {attrs_str} src="{src}"></script>'

@staticmethod
def stylesheet(href: str) -> Tag:
def stylesheet(href: str, attrs: Optional[Dict[str, str]] = None) -> Tag:
"""
Generates an HTML <link> stylesheet tag for CSS.

Expand All @@ -47,10 +47,12 @@ def stylesheet(href: str) -> Tag:
str -- CSS link tag.
"""

return f'<link rel="stylesheet" href="{href}" />'
attrs_str = attrs_to_str(attrs if attrs else {})

return f'<link {attrs_str} rel="stylesheet" href="{href}" />'

@staticmethod
def stylesheet_preload(href: str) -> Tag:
def stylesheet_preload(href: str, attrs: Optional[Dict[str, str]] = None) -> Tag:
"""
Generates an HTML <link> preload tag for CSS.

Expand All @@ -61,7 +63,9 @@ def stylesheet_preload(href: str) -> Tag:
str -- CSS link tag.
"""

return f'<link rel="preload" href="{href}" as="style" />'
attrs_str = attrs_to_str(attrs if attrs else {})

return f'<link {attrs_str} rel="preload" href="{href}" as="style" />'

@staticmethod
def preload(href: str, attrs: Dict[str, str]) -> Tag:
Expand Down
11 changes: 8 additions & 3 deletions tests/tests/templatetags/test_vite_asset.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,9 +218,14 @@ def test_vite_asset_kebab_attribute():
)
html = template.render(Context({}))
soup = BeautifulSoup(html, "html.parser")
script_tag = soup.find("script")
assert script_tag["data-item-track"] == "reload"
assert script_tag["data-other"] == "3"

for script_tag in soup.find_all("script"):
assert script_tag["data-item-track"] == "reload"
assert script_tag["data-other"] == "3"

for link in soup.find_all("link"):
assert link["data-item-track"] == "reload"
assert link["data-other"] == "3"


def test_vite_asset_custom_attributes(dev_mode_all):
Expand Down
Loading