PythonHTMLTemplates

From Traxel Wiki
Jump to navigation Jump to search


Install Jinja2

./.venv/bin/activate
pip install Jinja2

HTML Template

<!DOCTYPE html>
<html>
<head>
    <title>{{ title }}</title>
</head>
<body>
    <h1>{{ header }}</h1>
    <p>{{ message }}</p>
</body>
</html>

Python

from jinja2 import Template

# Read the template file
with open('template.html', 'r') as file:
    template_content = file.read()

template = Template(template_content)

# Render the template with variables
rendered_html = template.render(
    title='My Page',
    header='Welcome!',
    message='This is a message from the Python script.'
)

print(rendered_html)