- Jinja2 · PyPI
- Primer on Jinja Templating – Real Python
- https://jinja.palletsprojects.com/
- https://github.com/pallets/jinja/
Installing
Set up a virtual environment
> python -m venv venv > .\venv\Scripts\activate (venv) >
ติดตั้ง Jinja2 (จะได้ MarkupSafe มาด้วย)
$ pip install -U Jinja2
> pip list Package Version ---------- ------- Jinja2 3.1.2 MarkupSafe 2.1.3 pip 23.0.1 setuptools 65.5.
Example 1
import jinja2 environment = jinja2.Environment() template = environment.from_string("Hello, {{ name }}!") st = template.render(name="World") print(type(st)) print(st) # <class 'str'> # Hello, World!
Example 2 – Use an External File as a Template
{# templates/message.txt #} Hello {{ name }}! I'm happy to inform you that you did very well on today's {{ test_name }}. You reached {{ score }} out of {{ max_score }} points. See you tomorrow! Anke
# write_messages.py from jinja2 import Environment, FileSystemLoader max_score = 100 test_name = "Python Challenge" students = [ {"name": "Sandrine", "score": 100}, {"name": "Gergeley", "score": 87}, {"name": "Frieda", "score": 92}, ] environment = Environment(loader=FileSystemLoader("templates/")) template = environment.get_template("message.txt") for student in students: filename = f"message_{student['name'].lower()}.txt" content = template.render( student, max_score=max_score, test_name=test_name ) with open(filename, mode="w", encoding="utf-8") as message: message.write(content) print(f"... wrote {filename}") # ... wrote message_sandrine.txt # ... wrote message_gergeley.txt # ... wrote message_frieda.txt
รันเสร็จจะได้ไฟล์มา 3 ไฟล์
Example 3 – if
{# 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
# write_messages.py # ... students = [ {"name": "Sandrine", "score": 100}, {"name": "Gergeley", "score": 87}, {"name": "Frieda", "score": 92}, {"name": "Fritz", "score": 40}, {"name": "Sirius", "score": 75}, ] # ...
Example 4 – 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> {% if student.score > 80 %}?{% else %}?{% endif %} <em>{{ student.name }}:</em> {{ student.score }}/{{ max_score }} </li> {% endfor %} </ul> </body> </html>
# write_messages.py # ... results_filename = "students_results.html" results_template = environment.get_template("results.html") context = { "students": students, "test_name": test_name, "max_score": max_score, } with open(results_filename, mode="w", encoding="utf-8") as results: results.write(results_template.render(context)) print(f"... wrote {results_filename}")