PythonHTMLTemplates: Difference between revisions
Jump to navigation
Jump to search
No edit summary |
|||
(3 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
[[Category:Python]] | [[Category:Python]] | ||
= Links = | |||
* Jinja2 Primer: https://realpython.com/primer-on-jinja-templating/ | |||
= Install Jinja2 = | = Install Jinja2 = | ||
<pre> | <pre> | ||
Line 39: | Line 40: | ||
print(rendered_html) | print(rendered_html) | ||
</syntaxhighlight> | </syntaxhighlight> | ||
= Conditionals = | |||
<pre> | |||
{# 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 | |||
</pre> | |||
= Loops = | |||
<pre> | |||
{# 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> | |||
</pre> |
Latest revision as of 23:35, 7 January 2024
Links
- Jinja2 Primer: https://realpython.com/primer-on-jinja-templating/
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>