PythonHTMLTemplates: Difference between revisions
Jump to navigation
Jump to search
(→Python) |
No edit summary |
||
Line 23: | Line 23: | ||
<syntaxhighlight lang="python" line> | <syntaxhighlight lang="python" line> | ||
from jinja2 import Template | 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) | |||
</syntaxhighlight> | </syntaxhighlight> | ||
= Conditionals = | = Conditionals = | ||
Line 72: | Line 87: | ||
</html> | </html> | ||
</pre> | </pre> | ||
Revision as of 23:35, 7 January 2024
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)
Conditionals
{# templates/message.txt #} Hello {{ name }}! {% if score > 80 %} I'm happy to inform you that you did very well on today's {{ test_name }}. {% else %} I'm sorry to inform you that you did not do so well on today's {{ test_name }}. {% endif %} You reached {{ score }} out of {{ max_score }} points. See you tomorrow! Anke
Loops
{# templates/results.html #} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Results</title> </head> <body> <h1>{{ test_name }} Results</h1> <ul> {% for student in students %} <li> <em>{{ student.name }}:</em> {{ student.score }}/{{ max_score }} </li> {% endfor %} </ul> </body> </html>