Python 如何将HTML模板的动态部分拼接在一起并作为一个HTML打印
这是我的 template.py
文件:
first = '''<html><head></head>
<body>
<h1>This is header H1</h1>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Phone</th>
<th>Email</th>
</tr>
<tr>
<td>'''
uid='{uid}'
second='''</td>
<td>'''
name='{name}'
third='''</td>
<td>'''
phone='{phone}'
fourth='''</td>
<td>'''
email='{email}'
fifth='''</td>
</tr>
</table>
</body>
</html>'''
我打算把这个发邮件,但我觉得如果我打印出预期的结果,它应该能正常工作。
我有一个这样的列表:
list1 = [
{'uid': 1, 'name': 'saeed1', 'phone': '+989100000000', 'email': 'sample1@gmail.com'},
{'uid': 2, 'name': 'saeed2', 'phone': '+989200000000', 'email': 'sample2@gmail.com'},
{'uid': 3, 'name': 'saeed3', 'phone': '+989300000000', 'email': 'sample3@gmail.com'},
{'uid': 4, 'name': 'saeed4', 'phone': '+989400000000', 'email': 'sample4@gmail.com'},
]
我期望的输出是:
<html><head></head>
<body>
<h1>This is header H1</h1>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Phone</th>
<th>Email</th>
</tr>
<tr>
<td>1</td>
<td>saeed1</td>
<td>+989100000000</td>
<td>sample1@gmail.com</td>
</tr>
<tr>
<td>2</td>
<td>saeed2</td>
<td>+989200000000</td>
<td>sample2@gmail.com</td>
</tr>
<tr>
<td>3</td>
<td>saeed3</td>
<td>+989300000000</td>
<td>sample3@gmail.com</td>
</tr>
<tr>
<td>4</td>
<td>saeed4</td>
<td>+989400000000</td>
<td>sample4@gmail.com</td>
</tr>
</table>
</body>
</html>
这是我的尝试:
import template
for n in list1:
uid = template.uid.format(uid=n['uid'])
name = template.name.format(name=n['name'])
phone = template.phone.format(phone=n['phone'])
email = template.email.format(email=n['email'])
combined = template.first + uid + template.second + name + template.third + phone + template.fourth + email + template.fifth
print(combined)
我知道这样做是不对的,我觉得像 template.first
、template.second
这些静态的对象应该放在 for
循环外面,但我不知道接下来该怎么做,也不知道怎么把它们结合起来。
1 个回答
3
这可能是一个解决方案,希望能对你有所帮助。
start_document = '''<html><head></head>
<body>
<h1>This is header H1</h1>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Phone</th>
<th>Email</th>
</tr>
'''
added_content ='<tr><td>{uid}</td><td>{name}</td><td>{phone}</td><td>{email}</td></tr>'
end_document = '</table></body></html>'
list1 = [
{'uid': 1, 'name': 'saeed1', 'phone': '+989100000000', 'email': 'sample1@gmail.com'},
{'uid': 2, 'name': 'saeed2', 'phone': '+989200000000', 'email': 'sample2@gmail.com'},
{'uid': 3, 'name': 'saeed3', 'phone': '+989300000000', 'email': 'sample3@gmail.com'},
{'uid': 4, 'name': 'saeed4', 'phone': '+989400000000', 'email': 'sample4@gmail.com'},
]
filled_table = ''
for part_content in list1:
filled_table_row = added_content.format(**part_content)
filled_table += filled_table_row
total_document = start_document + filled_table + end_document
print(total_document)