Source code for superdjango.assets.library.javascript

# Imports

from django.conf import settings
from django.utils.safestring import mark_safe
from .base import Asset

# Exports

__all__ = (
    "JavaScript",
    "ScriptElement",
)

# Classes


[docs]class JavaScript(Asset): """A collection of JavaScript content and URLs."""
[docs] def append(self, identifier, content=None, url=None, wrap=True): """Add JavaScript to the collection.""" if identifier in self._identifiers: raise ValueError("Duplicate javascript identifier: %s" % identifier) if not content and not url: raise ValueError("Either content or url is required.") if url is not None: if url.startswith("http") or url.startswith("/"): src = url else: src = "%s%s" % (settings.STATIC_URL, url) _content = '<script src="%s"></script>' % src else: if wrap: _content = '<script>%s</script>' % content else: _content = content script = ScriptElement(identifier, content=_content) self._identifiers.append(identifier) self._items.append(script) return script
class ScriptElement(object): """A script to be included in a :py:class:`JavaScript` collection. This class is not used directly, but is added via the ``append()`` method of the collection. """ def __init__(self, identifier, content=None): """Initialize the script. :param identifier: The unique identifier for the content. :type identifier: str :param content: The content of the script. :type content: str """ self.content = content or "<!-- empty javascript: %s -->" % identifier self.identifier = identifier def __str__(self): return self.to_html() def to_html(self): """Export the script as HTML; automatically calls ``mark_safe()``. :rtype: str """ a = list() a.append("<!-- %s -->" % self.identifier) a.append(self.content) return mark_safe("\n".join(a))