欢迎访问宙启技术站
智能推送

使用Python的template()函数进行HTML模板替换的实例

发布时间:2023-12-29 09:31:10

在Python中,可以使用内置的template模块来进行HTML模板替换。这个模块提供了一个Template类,可以帮助我们动态地替换HTML模板中的变量。

下面是一个使用template函数进行HTML模板替换的实例:

from string import Template

# 定义HTML模板
html_template = """
<!DOCTYPE html>
<html>
<head>
    <title>$title</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
        }
        
        h1 {
            color: #333;
        }
        
        .red-text {
            color: red;
        }
    </style>
</head>
<body>
    <h1>$title</h1>
    <p>Welcome to $name's website!</p>
    <p class="red-text">$message</p>
</body>
</html>
"""

# 创建一个Template对象
template = Template(html_template)

# 定义要替换的变量
data = {
    'title': 'My Website',
    'name': 'John',
    'message': 'This is a sample message.'
}

# 使用substitute方法进行替换
output = template.substitute(data)

# 输出替换后的HTML代码
print(output)

在上面的例子中,首先定义了一个包含变量的HTML模板。然后,创建了一个Template对象,并使用substitute方法进行变量替换。最后,通过print函数输出替换后的HTML代码。

运行上面的代码,输出的HTML代码如下所示:

<!DOCTYPE html>
<html>
<head>
    <title>My Website</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
        }
        
        h1 {
            color: #333;
        }
        
        .red-text {
            color: red;
        }
    </style>
</head>
<body>
    <h1>My Website</h1>
    <p>Welcome to John's website!</p>
    <p class="red-text">This is a sample message.</p>
</body>
</html>

可以看到,所有的变量都被成功地替换为相应的值。

substitute方法还支持一种更简洁的替换方式,使用${}包裹变量名。上面的例子可以改写为:

# 使用$符号替换变量
output = template.safe_substitute(**data)

# 输出替换后的HTML代码
print(output)

上述代码与之前的代码功能相同,只是使用了safe_substitute方法,并使用了**操作符来将字典作为关键字参数传递给safe_substitute方法。

以上就是使用Python的template函数进行HTML模板替换的实例。通过template函数,我们可以动态地替换HTML模板中的变量,从而生成动态的HTML代码。这种方法非常适用于生成动态网页、电子邮件模板和报告等应用场景。