PythonHTMLTemplates

From Traxel Wiki
Revision as of 16:37, 10 November 2023 by RobertBushman (talk | contribs) (Created page with "Category:Python = Install Jinja2 = <pre> ./.venv/bin/activate pip install jinja2 </pre> = HTML Template = <syntaxhighlight lang="html" line> <!DOCTYPE html> <html> <head> <title>{{ title }}</title> </head> <body> <h1>{{ header }}</h1> <p>{{ message }}</p> </body> </html> </syntaxhighlight> = Python = <syntaxhighlight lang="python" line> from jinja2 import Template # Read the template file with open('template.html', 'r') as file: template_content = f...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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)