Tester
Tester

Reputation: 43

Pass variable python 3 and html

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>

Upvotes: 2

Views: 549

Answers (1)

C.K.
C.K.

Reputation: 1571

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.

Upvotes: 2

Related Questions