我不能将变量或数组传递给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>发布于 2020-03-30 20:43:03
您需要的是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工具。
https://stackoverflow.com/questions/60929932
复制相似问题