Search code examples
pythoncherrypy

Passing variables to html file on Python


I'm using the following function to execute a simple HTML view:

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

Our index.html file is:

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

How can I pass the {var} variable to the view from my controller?

I'm using CherryPy microframework to run the HTTP server and I'm NOT using any template engine.


Solution

  • change your html file and format it.

    index.html

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

    The code

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

    The Output

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