Passing variables to html file on Python

39.6k views Asked by At

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.

4

There are 4 answers

1
TheLazyScripter On BEST ANSWER

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>
1
Shubham On

CherryPy does not provide any HTML template but its architecture makes it easy to integrate one. Popular ones are Mako or Jinja2.

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

0
Naresh Kumar On

Below code is working fine. Change the HTML and Python code accordingly

index.html

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

Python code

class Main:
    first_header = 'World!'

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

The Output

<body>
    <h1>Hello, World!</h1>
</body>
0
Michael Stachura On

Old question but I'll update a little bit.

More convenient way you can pass data to html template as dict.

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>

Python

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)

The output will be html file with given data in context.