# Imports
from django.forms.utils import flatatt
from django.utils.safestring import mark_safe
# Exports
__all__ = (
"Element",
)
# Classes
[docs]class Element(object):
"""Base class for HTML elements."""
[docs] def __init__(self, tag, classes=None, close_tag=None, content="", **kwargs):
"""Initialize the element.
:param tag: The HTML tag that opens the element.
:type tag: str
:param classes: A list of CSS classes to be applied to the element.
:type classes: list | str | tuple
:param close_tag: The HTML tag that closes the element.
:type close_tag: str
:param content: The content (inner HTML or text) of the element.
:type content: str
Additional keyword arguments are treated as attributes of the element.
"""
self.content = content
self._close_tag = close_tag
self._open_tag = tag
if type(classes) is str:
kwargs['class'] = classes
elif type(classes) in (list, tuple):
kwargs['class'] = " ".join(classes)
else:
pass
self._attributes = kwargs
def __getattr__(self, item):
return self._attributes.get(item)
def __repr__(self):
return "<%s %s:%s>" % (self.__class__.__name__, self._open_tag, self.attributes)
def __str__(self):
return self.to_html()
@property
def attributes(self):
"""Get the flattened attributes for the element.
:rtype: str
"""
return flatatt(self._attributes)
[docs] def get_close_tag(self):
"""Get the closing tag for the element.
:rtype: str
"""
if self._close_tag is not None:
return "</%s>" % self._close_tag
return "</%s>" % self._open_tag
[docs] def get_content(self):
"""Get the content of the tag.
:rtype: str
.. note::
Child classes may re-implement this as needed.
"""
return self.content
[docs] def get_open_tag(self):
"""Get the opening tag for the element.
:rtype: str
"""
return "<%s%s>" % (self._open_tag, flatatt(self._attributes))
[docs] def set_attribute(self, name, value):
"""Set the given attribute name.
:param name: The name of the attribute.
:type name: str
:param value: The value of the attribute.
"""
self._attributes[name] = value
[docs] @mark_safe
def to_html(self):
"""Get the element as HTML.
:rtype: str
"""
a = list()
a.append(self.get_open_tag())
a.append(self.get_content())
a.append(self.get_close_tag())
return "".join(a)