PythonHTMLTemplates: Difference between revisions

From Traxel Wiki
Jump to navigation Jump to search
No edit summary
 
(One intermediate revision 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 23: Line 24:
<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 88:
</html>
</html>
</pre>
</pre>
# 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>

Latest revision as of 23:35, 7 January 2024

Links

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>