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.forms.utils import flatatt
4from django.utils.safestring import mark_safe
6# Exports
8__all__ = (
9 "Element",
10)
12# Classes
15class Element(object):
16 """Base class for HTML elements."""
18 def __init__(self, tag, classes=None, close_tag=None, content="", **kwargs):
19 """Initialize the element.
21 :param tag: The HTML tag that opens the element.
22 :type tag: str
24 :param classes: A list of CSS classes to be applied to the element.
25 :type classes: list | str | tuple
27 :param close_tag: The HTML tag that closes the element.
28 :type close_tag: str
30 :param content: The content (inner HTML or text) of the element.
31 :type content: str
33 Additional keyword arguments are treated as attributes of the element.
35 """
36 self.content = content
37 self._close_tag = close_tag
38 self._open_tag = tag
40 if type(classes) is str:
41 kwargs['class'] = classes
42 elif type(classes) in (list, tuple):
43 kwargs['class'] = " ".join(classes)
44 else:
45 pass
47 self._attributes = kwargs
49 def __getattr__(self, item):
50 return self._attributes.get(item)
52 def __repr__(self):
53 return "<%s %s:%s>" % (self.__class__.__name__, self._open_tag, self.attributes)
55 def __str__(self):
56 return self.to_html()
58 @property
59 def attributes(self):
60 """Get the flattened attributes for the element.
62 :rtype: str
64 """
65 return flatatt(self._attributes)
67 def get_close_tag(self):
68 """Get the closing tag for the element.
70 :rtype: str
72 """
73 if self._close_tag is not None:
74 return "</%s>" % self._close_tag
76 return "</%s>" % self._open_tag
78 def get_content(self):
79 """Get the content of the tag.
81 :rtype: str
83 .. note::
84 Child classes may re-implement this as needed.
86 """
87 return self.content
89 def get_open_tag(self):
90 """Get the opening tag for the element.
92 :rtype: str
94 """
95 return "<%s%s>" % (self._open_tag, flatatt(self._attributes))
97 def set_attribute(self, name, value):
98 """Set the given attribute name.
100 :param name: The name of the attribute.
101 :type name: str
103 :param value: The value of the attribute.
105 """
106 self._attributes[name] = value
108 @mark_safe
109 def to_html(self):
110 """Get the element as HTML.
112 :rtype: str
114 """
115 a = list()
116 a.append(self.get_open_tag())
117 a.append(self.get_content())
118 a.append(self.get_close_tag())
120 return "".join(a)