【问题标题】:Passing variables to html file on Python在 Python 上将变量传递给 html 文件
【发布时间】:2016-12-28 03:21:09
【问题描述】:

我正在使用以下函数来执行一个简单的 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


    【解决方案1】:

    更改您的 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>
    

    【讨论】:

    • 我们可以在 html 模板中使用基于条件的格式和循环吗?不询问 django 上下文处理器。
    【解决方案2】:

    下面的代码工作正常。相应地更改 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>
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 问题是问如何将变量放入文件中,因为没有使用模板框架
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-07
      • 2018-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-26
      • 1970-01-01
      相关资源
      最近更新 更多