所以我想要一种简单的方法来从只有内联样式的python字典生成html(因为电子邮件)并且找不到任何我满意的东西所以我写了这个,
它使用起来非常简单,并且很容易添加样式到
<table style="margin: 3px">
<tr style="background-color: #7cc3a97d">
<th style="color: white">col1</th>
<th style="color: white">col2</th>
<th style="color: white">col3</th>
<th style="color: white">col4</th>
</tr>
<tr style="background-color: aliceblue">
<td style="padding: 1rem">value11</td>
<td style="padding: 1rem">value21</td>
<td style="padding: 1rem">value31</td>
<td style="padding: 1rem">value41</td>
</tr>
<tr style="background-color: #c2d4e4">
<td style="padding: 1rem">value12</td>
<td style="padding: 1rem">value22</td>
<td style="padding: 1rem">value32</td>
<td style="padding: 1rem">value42</td>
</tr>
<tr style="background-color: aliceblue">
<td style="padding: 1rem">value13</td>
<td style="padding: 1rem">value23</td>
<td style="padding: 1rem">value33</td>
<td style="padding: 1rem">value43</td>
</tr>
</table>
假设您有以下字典
myDict = {
'col1' : ['value11', 'value12', 'value13'],
'col2' : ['value21', 'value22', 'value23'],
'col3' : ['value31', 'value32', 'value33'],
'col4' : ['value41', 'value42', 'value43'],
}
它可以转换为
class HTML:
def __init__(self, Header, tableStyles = {}, trStyles = {}, thStyles = {}):
self.tableStyles = HTML._styleConverter(tableStyles)
trStyles = HTML._styleConverter(trStyles)
thStyles = HTML._styleConverter(thStyles)
self.rows = []
self.Header= f'<tr {trStyles} >'
for th in Header:
self.Header += f'\n<th {thStyles} >{th}</th>'
self.Header += '\n</tr>'
@staticmethod
def _styleConverter(styleDict : dict):
if styleDict == {}:
return ''
styles = ''
for [style, value] in styleDict.items():
styles +=f'{style}: {value};'
return f'style="{styles}"'
def addRow(self, row, trStyles = {}, tdStyles = {}):
trStyles = HTML._styleConverter(trStyles)
tdStyles = HTML._styleConverter(tdStyles)
temp_row = f'\n<tr {trStyles} >'
for td in row:
temp_row += f'\n<td {tdStyles} >{td}</td>'
temp_row += '\n</tr>'
self.rows.append(temp_row)
def __str__(self):
return \
f'''
<table {self.tableStyles} >
{self.Header}
{''.join(self.rows)}
</table>
'''
def dictionaryToHTMLTable(dict : dict):
html = HTML(Header = dict.keys(),
tableStyles={'margin': '3px'},
trStyles={'background-color': '#7cc3a97d'},
thStyles={ 'color': 'white'})
for i, row in enumerate(zip(*dict.values())):
print(row)
if i%2 == 0:
BGC = 'aliceblue'
else:
BGC = '#c2d4e4'
html.addRow(row, trStyles={'background-color' : BGC}, tdStyles={'padding': '1rem'})
return html
并输出
print(dictionaryToHTMLTable(myDict))