设计一个简单的模板引擎,利用`html`模块将变量插入到预定义的HTML模板中。请演示代码。

以下是一个简单的模板引擎的实现示例,使用 Python 的 html 模块将变量插入到预定义的 HTML 模板中。

import html

class SimpleTemplateEngine:
    def __init__(self):
        self.template = """
<!DOCTYPE html>
<html>
<head>
    <title>{title}</title>
</head>
<body>
    <h1>{heading}</h1>
    <p>{content}</p>
</body>
</html>
        """

    def render(self, title, heading, content):
        # 使用 html 模块的 escape 方法对变量进行转义
        escaped_title = html.escape(title)
        escaped_heading = html.escape(heading)
        escaped_content = html.escape(content)

        # 替换模板中的占位符
        rendered_html = self.template.format(
            title=escaped_title,
            heading=escaped_heading,
            content=escaped_content
        )
        return rendered_html

# 示例使用
if __name__ == "__main__":
    engine = SimpleTemplateEngine()
    result = engine.render(
        title="My Page",
        heading="Welcome to My Website",
        content="This is a simple template engine example."
    )
    print(result)

运行结果说明

运行上述代码后,生成的 HTML 输出如下:

<!DOCTYPE html>
<html>
<head>
    <title>My Page</title>
</head>
<body>
    <h1>Welcome to My Website</h1>
    <p>This is a simple template engine example.</p>
</body>
</html>

详细解析

  1. 模板定义:

    • 在 SimpleTemplateEngine 类中,模板是一个包含占位符的多行字符串 {title}, {heading}, 和 {content}。
  2. 变量转义:

    • 使用 html.escape 方法对用户提供的变量进行转义,防止 XSS(跨站脚本)攻击。例如,如果用户输入的 title 是 <script>alert('xss')</script>,转义后会变为安全的文本。
  3. 模板渲染:

    • 通过 format 方法将转义后的变量插入模板中,生成最终的 HTML 字符串。
  4. 示例运行:

    • 在 __main__ 块中,创建了一个模板引擎实例,并传入了三个变量:title, heading, 和 content。生成的 HTML 完全符合预期。

扩展功能

如果需要支持更复杂的模板功能,例如循环或条件语句,可以扩展此类。例如:

class AdvancedTemplateEngine:
    def __init__(self):
        self.template = """
<!DOCTYPE html>
<html>
<head>
    <title>{title}</title>
</head>
<body>
    <h1>{heading}</h1>
    <ul>
        {items}
    </ul>
</body>
</html>
        """

    def render_items(self, items):
        escaped_items = []
        for item in items:
            escaped_items.append(f"<li>{html.escape(item)}</li>")
        return '\n'.join(escaped_items)

    def render(self, title, heading, items):
        escaped_title = html.escape(title)
        escaped_heading = html.escape(heading)
        rendered_items = self.render_items(items)

        rendered_html = self.template.format(
            title=escaped_title,
            heading=escaped_heading,
            items=rendered_items
        )
        return rendered_html

# 示例使用
if __name__ == "__main__":
    engine = AdvancedTemplateEngine()
    result = engine.render(
        title="Advanced Page",
        heading="Items List",
        items=["Item 1", "Item 2", "Item 3"]
    )
    print(result)

运行结果

<!DOCTYPE html>
<html>
<head>
    <title>Advanced Page</title>
</head>
<body>
    <h1>Items List</h1>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
    </ul>
</body>
</html>

以上示例展示了如何逐步实现一个简单的模板引擎,并通过扩展支持更多功能。