PythonHTMLTemplates: Difference between revisions

From Traxel Wiki
Jump to navigation Jump to search
(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...")
 
Line 4: Line 4:
<pre>
<pre>
./.venv/bin/activate
./.venv/bin/activate
pip install jinja2
pip install Jinja2
</pre>
</pre>
= HTML Template =
= HTML Template =
<syntaxhighlight lang="html" line>
<syntaxhighlight lang="html" line>

Revision as of 16:37, 10 November 2023


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)