python-3.x - 传递变量 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>
解决方案
您需要的是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
。您应该参考他们的文档以了解更高级的用法,因为它不仅仅是一个更智能的str.format
工具str.replace
。
推荐阅读
- python - Spyder 通过 pip 安装但不可见
- postgresql - 如何更新具有不同值的许多行?
- azure - ADO 不允许用户在未打开项目的情况下在待办事项列中创建新任务或移动项目流
- python - 在 Python 中写入 CSV 并同时附加到列表的最佳方法
- c++ - C++ 无法访问由向量的迭代器返回的类中的公共属性
- c++ - 计算数组中重复元素的数量
- react-native - 条形图上的不同颜色反应原生
- python - 基于知道其他键值boto3获取数组内对象中的键/值
- python - 按列合并 2 个 Pandas 数据帧,不重复,并选择要保留的列
- j - 绘制一列精度浮点值