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

时间:2016-12-28 03:21:10

标签: python cherrypy

我正在使用以下函数来执行简单的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服务器而我没有使用任何模板引擎。

3 个答案:

答案 0 :(得分:2)

更改您的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 :(得分: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>

答案 2 :(得分:0)

  

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

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