2

I can't pass variable or array to html python. So how would I go about displaying the Python variable to HTML? main.py:

from http.server import HTTPServer, BaseHTTPRequestHandler
class Serv(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/":
            self.path = '/index.html'
        try:
            file_to_open = open(self.path[1:]).read()
            self.send_response(200)
        except:
            file_to_open = "File not found"
            self.send_response(404)
        self.end_headers()
        self.wfile.write(bytes(file_to_open, 'utf-8'))
httpd = HTTPServer(('localhost', 8080), Serv)
httpd.serve_forever()

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Hello world!</h1>
    {{var}}
</body>
</html>
1
  • You can use str.format to interpolate the value, or read about templating languages (e.g. Jinja) for a more thorough approach. Commented Mar 30, 2020 at 11:56

1 Answer 1

2

What you need is Jinja which is a template language for Python. First pip install Jinja2 to make sure you have already had it.

Take your HTML code as example, suppose you have index.html in your working directory:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Hello world!</h1>
    {{var}}
</body>
</html>

And you have Python code like this:

from jinja2 import Template

with open('index.html','r') as f:
    template = Template(f.read())
with open('rendered_index.html','w') as f:
    f.write(template.render(var='hello world'))

And you will get in rendered_index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Hello world!</h1>
    hello world
</body>
</html>

Of course, this is a very basic usage with Jinja2. You should refer to their doc for more advanced usage, since it's more than a smarter str.format and str.replace tool.

Sign up to request clarification or add additional context in comments.

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.