Hide keyboard shortcuts

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 

2 

3from django.forms.utils import flatatt 

4from django.utils.safestring import mark_safe 

5 

6# Exports 

7 

8__all__ = ( 

9 "Element", 

10) 

11 

12# Classes 

13 

14 

15class Element(object): 

16 """Base class for HTML elements.""" 

17 

18 def __init__(self, tag, classes=None, close_tag=None, content="", **kwargs): 

19 """Initialize the element. 

20 

21 :param tag: The HTML tag that opens the element. 

22 :type tag: str 

23 

24 :param classes: A list of CSS classes to be applied to the element. 

25 :type classes: list | str | tuple 

26 

27 :param close_tag: The HTML tag that closes the element. 

28 :type close_tag: str 

29 

30 :param content: The content (inner HTML or text) of the element. 

31 :type content: str 

32 

33 Additional keyword arguments are treated as attributes of the element. 

34 

35 """ 

36 self.content = content 

37 self._close_tag = close_tag 

38 self._open_tag = tag 

39 

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 

46 

47 self._attributes = kwargs 

48 

49 def __getattr__(self, item): 

50 return self._attributes.get(item) 

51 

52 def __repr__(self): 

53 return "<%s %s:%s>" % (self.__class__.__name__, self._open_tag, self.attributes) 

54 

55 def __str__(self): 

56 return self.to_html() 

57 

58 @property 

59 def attributes(self): 

60 """Get the flattened attributes for the element. 

61 

62 :rtype: str 

63 

64 """ 

65 return flatatt(self._attributes) 

66 

67 def get_close_tag(self): 

68 """Get the closing tag for the element. 

69 

70 :rtype: str 

71 

72 """ 

73 if self._close_tag is not None: 

74 return "</%s>" % self._close_tag 

75 

76 return "</%s>" % self._open_tag 

77 

78 def get_content(self): 

79 """Get the content of the tag. 

80 

81 :rtype: str 

82 

83 .. note:: 

84 Child classes may re-implement this as needed. 

85 

86 """ 

87 return self.content 

88 

89 def get_open_tag(self): 

90 """Get the opening tag for the element. 

91 

92 :rtype: str 

93 

94 """ 

95 return "<%s%s>" % (self._open_tag, flatatt(self._attributes)) 

96 

97 def set_attribute(self, name, value): 

98 """Set the given attribute name. 

99 

100 :param name: The name of the attribute. 

101 :type name: str 

102 

103 :param value: The value of the attribute. 

104 

105 """ 

106 self._attributes[name] = value 

107 

108 @mark_safe 

109 def to_html(self): 

110 """Get the element as HTML. 

111 

112 :rtype: str 

113 

114 """ 

115 a = list() 

116 a.append(self.get_open_tag()) 

117 a.append(self.get_content()) 

118 a.append(self.get_close_tag()) 

119 

120 return "".join(a)