Skip to content

Commit

Permalink
support kebab casing
Browse files Browse the repository at this point in the history
  • Loading branch information
kierangillblueberry committed Mar 13, 2024
1 parent ff6d7a9 commit e44df5f
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,24 @@ If you want to overrides default attributes just add them like new attributes :

Although it's recommended to keep the default `type="module"` attribute as ViteJS build scripts as ES6 modules.

You can also set attributes that require `kebab-casing` by padding `json_encoded_attributes`.

```python
from django.utils.safestring import SafeString

def your_view(request):
json_encoded_attributes = json.dumps({
"some-item": "3",
"some-other-item": "value",
})

render(request, template, context={ "json_encoded_attributes": SafeString(json_encoded_attributes) })
```

```html
{% vite_asset '<path to your asset>' json_encoded_attributes=json_encoded_attributes %}
```

## Vite Legacy Plugin

If you want to consider legacy browsers that don't support ES6 modules loading
Expand Down
4 changes: 4 additions & 0 deletions django_vite/core/asset_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,10 @@ def generate_vite_asset(
this asset in your page.
"""

json_encoded_attributes = kwargs.pop("json_encoded_attributes", "{}")
json_encoded_attributes = json.loads(json_encoded_attributes)
kwargs.update(json_encoded_attributes)

if self.dev_mode:
url = self._get_dev_server_url(path)
return TagGenerator.script(
Expand Down
22 changes: 22 additions & 0 deletions tests/tests/templatetags/test_vite_asset.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import pytest
from django.utils.safestring import SafeString
import json
from bs4 import BeautifulSoup
from django.template import Context, Template, TemplateSyntaxError
from django_vite.core.exceptions import (
Expand Down Expand Up @@ -208,6 +210,26 @@ def test_vite_asset_override_default_attribute():
assert script_tag["crossorigin"] == "anonymous"


@pytest.mark.usefixtures("dev_mode_all")
def test_vite_asset_kebab_attribute():
additional_attributes = {
"data-item-track": "reload",
"data-other": "3",
}
template = Template(
"""
{% load django_vite %}
{% vite_asset "src/entry.ts" json_encoded_attributes=json_encoded_attributes %}
""")
html = template.render(Context({
"json_encoded_attributes": SafeString(json.dumps(additional_attributes))
}))
soup = BeautifulSoup(html, "html.parser")
script_tag = soup.find("script")
assert script_tag["data-item-track"] == "reload"
assert script_tag["data-other"] == "3"


def test_vite_asset_custom_attributes(dev_mode_all):
template = Template(
"""
Expand Down

0 comments on commit e44df5f

Please sign in to comment.