Skip to content

Commit

Permalink
Merge pull request #142 from kierangillblueberry/propagate-vite-asset…
Browse files Browse the repository at this point in the history
…-attrs

Make attributes set by the user propagate to all assets
  • Loading branch information
Niicck authored Sep 16, 2024
2 parents 7efe7d4 + e29d053 commit 9bbd7a2
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 16 deletions.
22 changes: 14 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 @@ -438,6 +439,7 @@ def _generate_css_files_of_asset(
already_processed_js: Optional[Set[str]] = None,
already_processed_css: Optional[Set[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 Down Expand Up @@ -467,7 +469,11 @@ def _generate_css_files_of_asset(
new_already_processed_js,
new_already_processed_css,
) = self._generate_css_files_of_asset(
import_path, already_processed_js, already_processed_css, tag_generator
import_path,
already_processed_js,
already_processed_css,
tag_generator,
attrs,
)
already_processed_js.update(new_already_processed_js)
already_processed_css.update(new_already_processed_css)
Expand All @@ -477,7 +483,7 @@ def _generate_css_files_of_asset(
if css_path in already_processed_css:
continue
url = self._get_production_server_url(css_path)
tags.append(tag_generator(url))
tags.append(tag_generator(url, attrs=attrs))
already_processed_css.add(css_path)

return self.GeneratedCssFilesOutput(
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 @@ -220,9 +220,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

0 comments on commit 9bbd7a2

Please sign in to comment.