如何在Python 3中向HTML传递并显示变量或数组?
如何在HTML页面中显示Python变量(基于http.server)
你的问题根源在于:当前代码只是静态读取并返回HTML文件内容,没有对HTML里的{{var}}占位符做任何模板渲染处理,所以它会直接以文本形式显示在页面上,而不是替换成Python变量的值。
下面给你几种不同复杂度的解决方案,按需选择:
方案1:简单字符串替换(适合单变量/极简场景)
如果只是传递少量简单变量,直接用字符串替换就够了,不需要额外依赖。修改你的main.py如下:
from http.server import HTTPServer, BaseHTTPRequestHandler class Serv(BaseHTTPRequestHandler): def do_GET(self): if self.path == "/": self.path = '/index.html' try: # 读取HTML文件内容(用with语句更安全) with open(self.path[1:], 'r', encoding='utf-8') as f: file_to_open = f.read() # 定义要传递的Python变量 my_variable = "这是从Python后端传过来的内容!" # 替换HTML中的{{var}}占位符 file_to_open = file_to_open.replace("{{var}}", my_variable) self.send_response(200) except FileNotFoundError: file_to_open = "File not found" self.send_response(404) except Exception as e: file_to_open = f"Server error: {str(e)}" self.send_response(500) # 别忘了设置正确的Content-Type编码,避免中文乱码 self.send_header('Content-type', 'text/html; charset=utf-8') self.end_headers() self.wfile.write(bytes(file_to_open, 'utf-8')) httpd = HTTPServer(('localhost', 8080), Serv) httpd.serve_forever()
你的index.html不需要修改,保持原来的{{var}}占位符即可。
方案2:使用Python内置string.Template(规范的轻量模板)
如果需要传递多个变量,或者担心字符串替换的冲突(比如变量内容里刚好有{{var}}),可以用Python内置的string.Template,语法更规范。
首先修改main.py:
from http.server import HTTPServer, BaseHTTPRequestHandler from string import Template class Serv(BaseHTTPRequestHandler): def do_GET(self): if self.path == "/": self.path = '/index.html' try: with open(self.path[1:], 'r', encoding='utf-8') as f: template_content = f.read() # 创建模板对象,注意HTML里的占位符要改成$var格式 template = Template(template_content) # 定义变量字典,可以传多个变量 context = { 'var': "用string.Template传递的变量", 'greeting': "你好呀!" } # 渲染模板,替换所有占位符 file_to_open = template.substitute(context) self.send_response(200) except FileNotFoundError: file_to_open = "File not found" self.send_response(404) except Exception as e: file_to_open = f"Server error: {str(e)}" self.send_response(500) self.send_header('Content-type', 'text/html; charset=utf-8') self.end_headers() self.wfile.write(bytes(file_to_open, 'utf-8')) httpd = HTTPServer(('localhost', 8080), Serv) httpd.serve_forever()
对应的index.html要把占位符改成$var格式:
<!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> <p>$var</p> <p>$greeting</p> </body> </html>
方案3:使用Jinja2模板引擎(专业级复杂场景)
如果你的页面需要循环渲染数组、条件判断、过滤器等复杂逻辑,推荐用Jinja2——这是Python生态中最流行的模板引擎,很多Web框架(比如Flask、Django)都基于它。
首先安装Jinja2:
pip install jinja2
然后修改main.py:
from http.server import HTTPServer, BaseHTTPRequestHandler from jinja2 import Environment, FileSystemLoader # 设置Jinja2环境,加载当前目录下的模板文件 env = Environment(loader=FileSystemLoader('.')) class Serv(BaseHTTPRequestHandler): def do_GET(self): if self.path == "/": self.path = '/index.html' try: # 获取模板文件 template = env.get_template(self.path[1:]) # 定义变量上下文,可以传递字符串、数组、字典等任意Python对象 context = { 'var': "用Jinja2传递的变量", 'fruits': ['苹果', '香蕉', '橙子'] # 传递数组示例 } # 渲染模板,支持循环、条件等语法 file_to_open = template.render(context) self.send_response(200) except FileNotFoundError: file_to_open = "File not found" self.send_response(404) except Exception as e: file_to_open = f"Server error: {str(e)}" self.send_response(500) self.send_header('Content-type', 'text/html; charset=utf-8') self.end_headers() self.wfile.write(bytes(file_to_open, 'utf-8')) httpd = HTTPServer(('localhost', 8080), Serv) httpd.serve_forever()
对应的index.html可以使用Jinja2的强大语法,比如循环数组:
<!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> <p>{{var}}</p> <h3>我的水果列表:</h3> <ul> {% for fruit in fruits %} <li>{{fruit}}</li> {% endfor %} </ul> </body> </html>
内容的提问来源于stack exchange,提问作者Tester
相关产品推荐
相关产品推荐

