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

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>
  1. Read the template file

with open('template.html', 'r') as file:

   template_content = file.read()

template = Template(template_content)

  1. 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>