Skip to main content

script tag with additional attributes for django.forms.Media

Project description

https://github.com/matthiask/django-js-asset/workflows/Tests/badge.svg

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.

Usage

Use this to insert a script tag via forms.Media containing additional attributes (such as id and data-* for CSP-compatible data injection.):

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:

<script type="text/javascript" src="/static/asset.js"
    data-answer="42" id="asset-script"></script>

The attributes are automatically escaped. The data attributes may now be accessed inside asset.js:

var 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:

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:

<script id="widget-configuration" type="application/json">{"configuration": 42}</script>
<link href="/static/widget/style.css" media="all" rel="stylesheet">
<style media="all">p{color:red;}</style>
<script src="/static/widget/script.js" type="module"></script>

Compatibility

At the time of writing this app is compatible with Django 4.2 and better (up to and including the Django main branch), but have a look at the tox configuration for definitive answers.

Extremely experimental importmap support

django-js-asset ships an extremely experimental implementation adding support for using importmaps.

One of the reasons why importmaps are useful when used with Django is that this easily allows us to use the file name mangling offered for example by Django ManifestStaticFilesStorage without having to rewrite import statements in scripts themselves.

Browser support for multiple importmaps is not generally available; at the time of writing (February 2025) it’s not even clear if Mozilla wants to support them ever, so merging importmaps is – for now – the only viable way to use them in production. Because of this the implementation uses a global importmap variable where new entries can be added to and a context processor to make the importmap available to templates.

The importmap object can be imported from js_asset. Usage is as follows:

# static is an alias for Django's static() function used in the
# {% static %} template tag.
from js_asset import JS, static, importmap

# Run this during project initialization, e.g. in App.ready or whereever.
importmap.update({
    "imports": {
        "my-library": static("my-library.js"),
    },
})

You have to add js_asset.importmap.context_processor to the list of context processors in your settings (or choose some other way of making the importmap object available in templates) and add {{ importmap }} somewhere in your base template, preferrably at the top before including any scripts.

When you’ve done that you can start profiting from the importmap by adding JavaScript modules:

# Example for adding a code.js JavaScript *module*
forms.Media(js=[
    JS("code.js", {"type": "module"}),
])

The code in code.js can now use a JavaScript import to import assets from the library, even though the library’s filename may contain hashes not known at programming time:

import { Stuff } from "my-library"

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_js_asset-3.1.0.tar.gz (9.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_js_asset-3.1.0-py3-none-any.whl (6.0 kB view details)

Uploaded Python 3

File details

Details for the file django_js_asset-3.1.0.tar.gz.

File metadata

  • Download URL: django_js_asset-3.1.0.tar.gz
  • Upload date:
  • Size: 9.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: python-httpx/0.28.1

File hashes

Hashes for django_js_asset-3.1.0.tar.gz
Algorithm Hash digest
SHA256 b8855d9983174ea162c8fb2bfcb3c9ff559f373226554f196170c93f07597c3d
MD5 6cf86104fc80cf7893849937be5e4b6d
BLAKE2b-256 99b4b2876bb954caa8f8802578271fce4b84c4b55e1bc6fb3d7d393c2cd28371

See more details on using hashes here.

File details

Details for the file django_js_asset-3.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for django_js_asset-3.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2f71e1e3df9c33fdccd2d41a50214a649cce64a832b42e1df26a79135fd3e8bd
MD5 1d34218386e94201b9fb5c9431b837f9
BLAKE2b-256 a82cac508ecaf59f17b771555218608ce61fafbb7655d6011faa208e487e42e6

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page