-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathhtml_render.py
127 lines (84 loc) · 2.6 KB
/
html_render.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#!/usr/bin/env python3
"""
A class-based system for rendering html.
"""
# This is the framework for the base class
class Element:
tag = "html"
indent = 4
def __init__(self, content=None, **kwags):
if content:
self.contents = [content]
else: self.contents = []
self.tag_attributes = kwags
def _open_tag(self):
open_tag = ["<{}".format(self.tag)]
for key, value in self.tag_attributes.items():
open_tag.append(' {}="{}"'.format(key, value))
open_tag.append(">")
return "".join(open_tag)
def _close_tag(self):
return "</{}>".format(self.tag)
def append(self, new_content):
self.contents.append(new_content)
def render(self, out_file):
out_file.write(self._open_tag())
out_file.write("\n")
for content in self.contents:
try:
content.render(out_file)
except AttributeError:
out_file.write(content)
out_file.write("\n")
out_file.write(self._close_tag())
out_file.write("\n")
class Html(Element):
tag = "html"
doc = "<!DOCTYPE html>\n"
def render(self,out_file):
out_file.write(self.doc)
super().render(out_file)
class Body(Element):
tag = "body"
class P(Element):
tag = "p"
class Head(Element):
tag = "head"
class OneLineTag(Element):
def render(self, out_file):
out_file.write(self._open_tag())
out_file.write(self.contents[0])
out_file.write(self._close_tag())
def append(self, content):
raise NotImplementedError
class Title(OneLineTag):
tag = "title"
class SelfClosingTag(Element):
def __init__(self, content=None, **kwargs):
if content is not None:
raise TypeError("SelfClosingTag can not contain any content")
super().__init__(content=content, **kwargs)
def render(self, outfile):
tag = self._open_tag()[:-1] + " />\n"
outfile.write(tag)
def append(self, *args):
raise TypeError("You can not add content to a SelfClosingTag")
class Hr(SelfClosingTag):
tag = "hr"
class Br(SelfClosingTag):
tag = "br"
class A(OneLineTag):
tag = 'a'
def __init__(self, link, content=None, **kwargs):
kwargs['href'] = link
super().__init__(content, **kwargs)
class H(OneLineTag):
def __init__(self, level, content=None, **kwargs):
self.tag = "h" + str(level)
super().__init__(content, **kwargs)
class Ul(Element):
tag = "ul"
class Li(Element):
tag = "li"
class Meta(SelfClosingTag):
tag = "meta"