pip install pytemplatesforpythonStart with basic text:
Plain text
Add a variable:
Plain text written by {{ insert(name) }}
Use an object:
Plain text is written by {{ insert(author.name) }}
Some information about him:
He’s {{ insert(author.age) }} years old, he lives in {{ insert(author.city) }}
Wondering what else you can do?
The answer is: pretty much anything you can do in plain Python!
- Avoid using newline characters inside
{{ ... }}. - Want control structures like
for,while,if, etc.?
Use{{+}}to increase indentation and{{-}}to decrease it. - Expressions inside double braces can be sequential:
First{{ a = 3 }}, then{{ insert(a) }}.
Example:
Plain text is written by {{ insert(author.name) }}
Several facts about him:
{{ for i, fact in enumerate(author.facts): }}{{+}}
Fact №{{ insert(i) }}: {{ insert(fact) }}
{{-}}
Which will be rendered with indentation similar to:
for i, fact in enumerate(author.facts):
insert(i)
insert(fact)By default, all expressions reference a single context parameter.
To improve clarity, you can unpack it:
{{ man: Creature = context["man"] }}
{{ monkey: Creature = context["monkey"] }}
Man loves {{ insert(man.loves) }} and monkey loves {{ insert(monkey.loves) }}.
Man lives in {{ insert(man.lives_in) }}, monkey lives in {{ insert(monkey.lives_in) }}.
Most common use case is rendering HTML:
<!DOCTYPE html>
{{ author = context["author"] }}
<html>
<body>
<p>Plain text is written by {{ insert(author.name) }}</p>
<p>Several facts about him:</p>
<ul>
{{ for i, fact in enumerate(author.facts): }}{{+}}
<li>
Fact №{{ insert(i) }}: {{ insert(fact) }}.
</li>
{{-}}
</ul>
</body>
</html>from pytemplatesforpython import FileTemplatetemplate = FileTemplate("template.html")class Author:
def __init__(self, name, facts):
self.name = name
self.facts = facts
author = Author(
"Alexey",
["lives in Israel", "knows Python, Java, and JavaScript", "can’t think of more facts"]
)result = template.render({"author": author})print(result)with open("result.html", "w+") as file:
file.write(result)from django.http import HttpResponse
def view(req):
return HttpResponse(template.render({"author": author}))In a real project, you'll likely need multiple templates. Use TemplatesLoader for that.
from pytemplatesforpython import TemplatesLoaderloader = TemplatesLoader("templates/")Load one manually:
loader.load_template("example.html")Or load all templates recursively:
loader.recursively_load_folder()template = loader.get_template("example.html")🔹 All paths are relative to the directory you passed to
TemplatesLoader.