我目前正在用 Python 構建一個 HTML 渲染器,并讓這些類處理標簽:
class SingleTag:
"""A class to represent an html tag"""
# Class initialiser
def __init__(self, inner_html):
self.open_tag = "<" self.__class__.__name__.lower() ">"
self.close_tag = "</" self.__class__.__name__.lower() ">"
self.inner_html = inner_html
# Prints html
def render(self):
return self.open_tag self.inner_html self.close_tag
class ContainingTag:
def __init__(self, children):
self.open_tag = "<" self.__class__.__name__.lower() ">"
self.close_tag = "</" self.__class__.__name__.lower() ">"
self.children = children
def render(self):
print("\t" self.open_tag)
for child in self.children:
print("\t \t" str(child.render()))
print("\t" self.close_tag)
return ""
class Html(ContainingTag):
def __init__(self, children):
super().__init__(children)
self.open_tag = "<!DOCTYPE html>\n" "<" self.__class__.__name__.lower() ">"
def render(self):
print(self.open_tag)
for child in self.children:
print("\t \t" str(child.render()))
print(self.close_tag)
return ""
class Head(ContainingTag):
def __init__(self, children):
super().__init__(children)
class Style(ContainingTag):
def __init__(self, children):
super().__init__(children)
class Body(ContainingTag):
def __init__(self, children):
super().__init__(children)
class Div(ContainingTag):
def __init__(self, children):
super().__init__(children)
class P(SingleTag):
def __init__(self, inner_html):
super().__init__(inner_html)
from tag import Html, P, Div, Head, Style, Body
html = Html([
Div([
Head([])
])
])
print(html.render())
<!DOCTYPE html>
<html>
<div>
<head>
</head>
</div>
</html>
我的單個標簽可以在包含標簽內正常列印,但是在另一個包含標簽內列印包含標簽時,當我希望縮進時,縮進處于同一級別。有沒有辦法檢查一個包含標簽是否是另一個包含標簽的子標簽,所以我可以有條件地列印額外的縮進?
uj5u.com熱心網友回復:
我一直處理這樣的遞回縮進的方式是使用關鍵字引數render(或等效函式具有的任何名稱)。
property此外,您可以通過繼承類似于屬性的函式來節省大量代碼,而不是在__init__函式中設定靜態值。
class Tag:
@property
def open_tag(self): return f'<{self.__class__.__name__.lower()}>'
@property
def close_tag(self): return f'</{self.__class__.__name__.lower()}>'
def __str__(self):
return self.render()
class SingleTag(Tag):
def __init__(self, inner_html):
self.inner_html = inner_html
def render(self, indent=''):
return f'{indent}{self.open_tag}{self.inner_html}{self.close_tag}\n'
class ContainingTag(Tag):
def __init__(self, children):
self.children = children
def render(self, indent=''):
inner = ''.join(child.render(indent '\t') for child in self.children)
return f'{indent}{self.open_tag}\n{inner}{indent}{self.close_tag}\n'
class Html(ContainingTag):
'''HTML tag'''
@property
def open_tag(self): return '<!DOCTYPE html>\n<html>'
class Head(ContainingTag): '''HEAD tag'''
class Style(ContainingTag): '''STYLE tag'''
class Body(ContainingTag): '''BODY tag'''
class Div(ContainingTag): '''DIV tag'''
class P(SingleTag): '''P tag'''
然后:
html = Html([Div([Head([])])])
print(html)
<!DOCTYPE html>
<html>
<div>
<head>
</head>
</div>
</html>
注意:我在\t這里使用了每個級別的縮進,但是您可以使用對您的需要有意義的任何內容。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/463347.html
上一篇:無法在VUEjsTypescript中參考data()
下一篇:為什么我的物件渲染函式顯示無?
