1

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 Answers 4

13

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>
Sign up to request clarification or add additional context in comments.

1 Comment

can we use conditional based formatting and loops also in the html template? Not asking about django context processor.
1

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>

Comments

0

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

1 Comment

The question was asking how to put the variable into the file because there is no template framework used
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.