我无法将变量或数组传递给html python。那么如何将Python变量显示为HTML? main.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()
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>
您需要的是Jinja
,这是Python的模板语言。首先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
的非常基本的用法。您应该参考their doc以获得更高级的用法,因为它不仅仅是更智能的str.format
和str.replace
工具。