diff --git a/README.md b/README.md index 664f968..fc9810a 100644 --- a/README.md +++ b/README.md @@ -216,6 +216,49 @@ 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. +### Jinja2 template backend + +If you are using Django with the Jinja2 template backend then alternative versions of the templatetags are provided, via an Extension. + +If you are using [`django-jinja` library](https://niwi.nz/django-jinja/latest/#_add_additional_extensions) then you can: + +```python +from django_jinja.builtins import DEFAULT_EXTENSIONS + +"OPTIONS": { + "extensions": DEFAULT_EXTENSIONS + [ + # Your extensions here... + "django_vite.templatetags.jinja.DjangoViteExtension" + ] +} +``` + +Or for a [vanilla Django + Jinja2 setup](https://docs.djangoproject.com/fr/4.2/topics/templates/#django.template.backends.jinja2.Jinja2) you can do something like: + +```python +from django.templatetags.static import static +from django.urls import reverse + +from jinja2 import Environment +from django_vite.templatetags.jinja import DjangoViteExtension + + +def environment(**options): + options.setdefault("extensions", []).append(DjangoViteExtension) + env = Environment(**options) + return env +``` + +Then usage in your templates is similar, but adjusted as is normal for Jinja2 rather than Django template language. + +- Omit the `{% load django_vite %}` which is not needed. +- Replace tag syntax with function calls, e.g. + - `{% vite_react_refresh %}` becomes: + `{{ vite_react_refresh() }}` + - `{% vite_asset '' foo="bar" %}` becomes: + `{{ vite_asset('', foo="bar") }}` + etc + ## Vite Legacy Plugin If you want to consider legacy browsers that don't support ES6 modules loading diff --git a/django_vite/templatetags/base.py b/django_vite/templatetags/base.py new file mode 100644 index 0000000..e94fdc4 --- /dev/null +++ b/django_vite/templatetags/base.py @@ -0,0 +1,180 @@ +from typing import Dict + +from django_vite.core.asset_loader import DjangoViteAssetLoader, DEFAULT_APP_NAME + + +def vite_hmr_client(app: str = DEFAULT_APP_NAME, **kwargs: Dict[str, str]) -> str: + """ + Generates the script tag for the Vite WS client for HMR. + Only used in development, in production this method returns + an empty string. + + Arguments: + config {str} -- Configuration to use. + + Returns: + str -- The script tag or an empty string. + + Keyword Arguments: + **kwargs {Dict[str, str]} -- Adds new attributes to generated + script tags. + """ + + return DjangoViteAssetLoader.instance().generate_vite_ws_client(app, **kwargs) + + +def vite_asset( + path: str, + app: str = DEFAULT_APP_NAME, + **kwargs: Dict[str, str], +) -> str: + """ + Generates a