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 "StyleElement",
11 "StyleSheet",
12)
14# Classes
17class StyleElement(object):
18 """A style to be included in a :py:class:`StyleSheet` collection.
20 This class is not used directly, but is added via the ``append()`` method of the collection.
22 """
24 def __init__(self, identifier, content=None):
25 """Initialize the style.
27 :param identifier: The unique identifier for the content.
28 :type identifier: str
30 :param content: The content of the style.
31 :type content: str
33 """
34 self.content = content or "<!-- empty style: %s -->" % identifier
35 self.identifier = identifier
37 def __str__(self):
38 return self.to_html()
40 def to_html(self):
41 """Export the style as HTML; automatically calls ``mark_safe()``.
43 :rtype: str
45 """
46 a = list()
47 a.append("<!-- %s -->" % self.identifier)
48 a.append(self.content)
49 return mark_safe("\n".join(a))
52class StyleSheet(Asset):
53 """A collection of CSS styles."""
55 def append(self, identifier, content=None, url=None, wrap=True):
56 """Add CSS to the collection."""
57 if identifier in self._identifiers:
58 raise ValueError("Duplicate style identifier: %s" % identifier)
60 if not content and not url:
61 raise ValueError("Either content or url is required.")
63 if url is not None:
64 if url.startswith("http") or url.startswith("/"):
65 href = url
66 else:
67 href = "%s%s" % (settings.STATIC_URL, url)
69 _content = '<link rel="stylesheet" href="%s">' % href
70 else:
71 if wrap:
72 _content = '<style>%s</style>' % content
73 else:
74 _content = content
76 style = StyleElement(identifier, content=_content)
78 self._identifiers.append(identifier)
79 self._items.append(style)
81 return style