我正在使用以下函数来执行一个简单的 HTML 视图:
import cherrypy
class index(object):
@cherrypy.expose
def example(self):
var = "goodbye"
index = open("index.html").read()
return index
Run Code Online (Sandbox Code Playgroud)
我们的 index.html 文件是:
<body>
<h1>Hello, {var}!</h1>
</body>
Run Code Online (Sandbox Code Playgroud)
如何将 {var} 变量从我的控制器传递给视图?
我使用 CherryPy 微框架来运行 HTTP 服务器,我没有使用任何模板引擎。
更改您的 html 文件并对其进行格式化。
索引.html
<body>
<h1>Hello, {first_header:}!</h1>
<p>{p2:}, {p1:}!</p>
</body>
Run Code Online (Sandbox Code Playgroud)
编码
index = open("index.html").read().format(first_header='goodbye',
p1='World',
p2='Hello')
Run Code Online (Sandbox Code Playgroud)
输出
<body>
<h1>Hello, goodbye!</h1>
<p>Hello, World!</p>
</body>
Run Code Online (Sandbox Code Playgroud)