首页 > 解决方案 > 传递变量 python 3 和 html

问题描述

我无法将变量或数组传递给 html python。那么我将如何将 Python 变量显示为 HTML 呢?主要.py:

from http.server import HTTPServer, BaseHTTPRequestHandler
class Serv(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/":
            self.path = '/index.html'
        try:
            file_to_open = open(self.path[1:]).read()
            self.send_response(200)
        except:
            file_to_open = "File not found"
            self.send_response(404)
        self.end_headers()
        self.wfile.write(bytes(file_to_open, 'utf-8'))
httpd = HTTPServer(('localhost', 8080), Serv)
httpd.serve_forever()

索引.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Hello world!</h1>
    {{var}}
</body>
</html>

标签: python-3.x

解决方案


您需要的是JinjaPython 的模板语言。首先pip install Jinja2要确保你已经拥有它。

以您的 HTML 代码为例,假设您index.html的工作目录中有:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Hello world!</h1>
    {{var}}
</body>
</html>

你有这样的 Python 代码:

from jinja2 import Template

with open('index.html','r') as f:
    template = Template(f.read())
with open('rendered_index.html','w') as f:
    f.write(template.render(var='hello world'))

你将进入rendered_index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Hello world!</h1>
    hello world
</body>
</html>

当然,这是一个非常基本的用法Jinja2。您应该参考他们的文档以了解更高级的用法,因为它不仅仅是一个更智能的str.format工具str.replace


推荐阅读