我得到了一个带有预定义变量的 HTML 模板。我想给变量赋值。
我的模板:
temp_string = """<td style="font-size:18px;">Dear {{var:name:"user"}}, welcome and congratulations on joining stack. Your age is {{var:age:"0"}}</td></tr>"""
Run Code Online (Sandbox Code Playgroud)
我的字典:
my_data = {'name': 'Foo', 'age': 20}
Run Code Online (Sandbox Code Playgroud)
最终输出
"""<td style="font-size:18px;">Dear Foo, welcome and congratulations on joining stack. Your age is 20</td></tr>"""
Run Code Online (Sandbox Code Playgroud)
我的代码
>>> temp_string = """<td style="font-size:18px;">Dear {{var:name:"user"}}, welcome and congratulations on joining stack. Your age is {{var:age:"0"}}</td></tr>"""
>>> my_data = {'name': 'Foo', 'age': 20}
>>> for key,value in my_data.items():
... if key in temp_string:
... temp_string.replace(key, value)
Run Code Online (Sandbox Code Playgroud)
干得好...
re.sub()有一个表单接受一个函数,该函数将返回给定匹配对象的替换值。
var:,然后将其拆分为三个部分(最多拆分为 2 个拆分)。var:,则逐字传递。您可能想要引发错误。ast.literal_eval()它们。import re
import ast
def replace_placeholders(template, data):
def replacer(match):
content = match.group(1)
if content.startswith("var:"):
_, name, quoted_default = content.split(":", 2)
if name in data:
return str(data[name])
return str(ast.literal_eval(quoted_default))
# Pass other content through as-is
return match.group(0)
return re.sub(r"{{(.+?)}}", replacer, template)
print(
replace_placeholders(
template="""Dear {{var:name:"user"}}, welcome and congratulations on joining stack. Your age is {{var:age:"0"}}""",
data={"name": "Foo", "age": 20},
)
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
62 次 |
| 最近记录: |