在 Python 上将变量传递给 html 文件

问题描述 投票:0回答:4

我正在使用以下函数来执行一个简单的 HTML 视图:

import cherrypy
class index(object):
    @cherrypy.expose
    def example(self):
        var = "goodbye"
        index = open("index.html").read()
        return index

我们的index.html文件是:

<body>
    <h1>Hello, {var}!</h1> 
</body>

如何将 {var} 变量从我的控制器传递到视图?

我正在使用 CherryPy 微框架来运行 HTTP 服务器并且我没有使用任何模板引擎。

python cherrypy
4个回答
12
投票

更改您的 html 文件并对其进行格式化。

index.html

<body>
    <h1>Hello, {first_header:}!</h1>
    <p>{p2:}, {p1:}!</p>
</body>

代码

index = open("index.html").read().format(first_header='goodbye', 
                                         p1='World', 
                                         p2='Hello')

输出

<body>
    <h1>Hello, goodbye!</h1>
    <p>Hello, World!</p>
</body>

1
投票

下面的代码工作正常。相应地更改 HTML 和 Python 代码

index.html

<body>
    <h1>Hello, {p.first_header}</h1>
</body>

Python代码

class Main:
    first_header = 'World!'

# Read the HTML file
HTML_File=open('index.html','r')
s = HTML_File.read().format(p=Main())
print(s)

输出

<body>
    <h1>Hello, World!</h1>
</body>

0
投票

CherryPy 不提供任何 HTML 模板,但其架构使其易于集成。流行的是MakoJinja2

来源:http://docs.cherrypy.org/en/latest/advanced.html#html-templating-support


0
投票

老问题,但我会更新一点。

更方便的方式,您可以将数据作为字典传递给 html 模板。

index.html

<html>
<head>
    <meta charset="UTF-8">
    <title>Invoice</title>
</head>
<body>
    <h1>Invoice</h1>
    <table>
        <tr>
            <th>Description</th>
            <th>Quantity</th>
            <th>Price</th>
            <th>Total</th>
        </tr>
        <tr>
          <td>{invoice_number}</td>
          <td>{date}</td>
          <td>{customer_name}</td>
          <td>{total}</td>
        </tr>
</body>
</html>

蟒蛇

context = {
    "invoice_number": "12345",
    "date": "2023-04-25",
    "customer_name": "John Doe",
    "total": 85,
}

with open("index.html", "r") as file:
    html = file.read().format(**context)

输出将是在上下文中包含给定数据的 html 文件。

© www.soinside.com 2019 - 2024. All rights reserved.