Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Imports
3from django.conf import settings
4from django.utils.safestring import mark_safe
5from .base import Asset
7# Exports
9__all__ = (
10 "JavaScript",
11 "ScriptElement",
12)
14# Classes
17class JavaScript(Asset):
18 """A collection of JavaScript content and URLs."""
20 def append(self, identifier, content=None, url=None, wrap=True):
21 """Add JavaScript to the collection."""
22 if identifier in self._identifiers:
23 raise ValueError("Duplicate javascript identifier: %s" % identifier)
25 if not content and not url:
26 raise ValueError("Either content or url is required.")
28 if url is not None:
29 if url.startswith("http") or url.startswith("/"):
30 src = url
31 else:
32 src = "%s%s" % (settings.STATIC_URL, url)
34 _content = '<script src="%s"></script>' % src
35 else:
36 if wrap:
37 _content = '<script>%s</script>' % content
38 else:
39 _content = content
41 script = ScriptElement(identifier, content=_content)
43 self._identifiers.append(identifier)
44 self._items.append(script)
46 return script
49class ScriptElement(object):
50 """A script to be included in a :py:class:`JavaScript` collection.
52 This class is not used directly, but is added via the ``append()`` method of the collection.
54 """
56 def __init__(self, identifier, content=None):
57 """Initialize the script.
59 :param identifier: The unique identifier for the content.
60 :type identifier: str
62 :param content: The content of the script.
63 :type content: str
65 """
66 self.content = content or "<!-- empty javascript: %s -->" % identifier
67 self.identifier = identifier
69 def __str__(self):
70 return self.to_html()
72 def to_html(self):
73 """Export the script as HTML; automatically calls ``mark_safe()``.
75 :rtype: str
77 """
78 a = list()
79 a.append("<!-- %s -->" % self.identifier)
80 a.append(self.content)
81 return mark_safe("\n".join(a))