我们有下面的html代码,它用一个可变在python中调用
html123='''
<html>
<head>
<style>
div {
background-color: lightgrey;
width: 300px;
border: 15px solid green;
padding: 50px;
margin: 20px;
}
</style>
</head>
<body>
<h2>Demonstrating the Box Model</h2>
<div>This text is $Var1</div>
</body>
</html>
</html> '''
对于一个变量,我在下面尝试
from string import Template
s = Template(html123).safe_substitute(Var1=LockingVar)
如果我有多个变量
html123='''
<html>
<head>
<style>
div {
background-color: lightgrey;
width: 300px;
border: 15px solid green;
padding: 50px;
margin: 20px;
}
</style>
</head>
<body>
<h2>Demonstrating the Box Model</h2>
<div>This text is $Var1</div>
<div>This text is $Var2</div>
<div>This text is $Var3</div>
</body>
</html>
</html> '''
但如果html标签中有多个变量Var1、var2、var3,我们如何映射这些变量的值。
请有什么建议。。
提供一个dict以安全取代
>>> params = {
... 'Var1':'aa',
... 'Var2':'bb',
... 'Var3':'cc'
... }
>>> Template("$Var1 $Var2 $Var3").safe_substitute(params)
"aa bb cc"