==================================================================
django-js-asset -- JS, CSS and JSON support for django.forms.Media
==================================================================
**Note!** `Django 5.2 adds its own support for JavaScript objects
`__.
This library has a slightly different API and also supports much older
versions
of Django, *and* it also supports CSS and JSON tags. As of the next version
JS and CSS actually *produce* Django's own Script and Stylesheet
objects (backported on Django versions that lack them), so js_asset assets,
plain path strings and Django's native assets share the same de-duplication
buckets in ``forms.Media`` -- see `Deduplication`_ below.
.. warning::
**Upgrading from 3.x?** django-js-asset 4.0 is somewhat different,
especially
if you use **import maps**: the global importmap object and its context
processor have been removed in favour of merging ImportMap objects
through the new ``js_asset.Media`` class (see `Import maps`_ below).
Read the
[change log
] before
upgrading.
Usage
=====
Use this to insert a script tag via ``forms.Media`` containing additional
attributes (such as id and ``data-*`` for CSP-compatible data
injection.):
.. code-block:: python
from js_asset import JS
forms.Media(js=[
JS("asset.js", {
"id": "asset-script",
"data-answer": "42",
}),
])
The rendered media tag (via ``{{ media.js }} or {{ media }}`` will
now contain a script tag as follows, without line breaks:
.. code-block:: html
The attributes are automatically escaped. The data attributes may now be
accessed inside ``asset.js``:
.. code-block:: javascript
let answer = document.querySelector("#asset-script").dataset.answer;
Also, because the implementation of static differs between supported
Django versions (older do not take the presence of
``django.contrib.staticfiles in INSTALLED_APPS`` into account), a
``js_asset.static`` function is provided which does the right thing
automatically.
CSS and JSON support
====================
Since 3.0 django-js-asset also ships a CSS and JSON media object which
can be used to ship stylesheets, inline styles and JSON blobs to the
frontend.
It's recommended to pass those through ``forms.Media(js=[]) as well since
js is a simple list while css`` uses a dictionary keyed with the media to
use for the stylesheet.
So, you can add everything at once:
.. code-block:: python
from js_asset import CSS, JS, JSON
forms.Media(js=[
JSON({"configuration": 42}, id="widget-configuration"),
CSS("widget/style.css"),
CSS("p{color:red;}", inline=True),
JS("widget/script.js", {"type": "module"}),
])
This produces:
.. code-block:: html
Inline CSS is rendered verbatim -- a ``