# Imports
from django.conf import settings
from django.utils.safestring import mark_safe
from .base import Asset
# Exports
__all__ = (
"StyleElement",
"StyleSheet",
)
# Classes
class StyleElement(object):
"""A style to be included in a :py:class:`StyleSheet` 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 style.
:param identifier: The unique identifier for the content.
:type identifier: str
:param content: The content of the style.
:type content: str
"""
self.content = content or "<!-- empty style: %s -->" % identifier
self.identifier = identifier
def __str__(self):
return self.to_html()
def to_html(self):
"""Export the style 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))
[docs]class StyleSheet(Asset):
"""A collection of CSS styles."""
[docs] def append(self, identifier, content=None, url=None, wrap=True):
"""Add CSS to the collection."""
if identifier in self._identifiers:
raise ValueError("Duplicate style 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("/"):
href = url
else:
href = "%s%s" % (settings.STATIC_URL, url)
_content = '<link rel="stylesheet" href="%s">' % href
else:
if wrap:
_content = '<style>%s</style>' % content
else:
_content = content
style = StyleElement(identifier, content=_content)
self._identifiers.append(identifier)
self._items.append(style)
return style