Monday, January 05, 2026

Here’s a little trick I use to sneak some metadata into my Mako templates.

You can define python methods as top-level definitions in a Mako template. Then, from the python side, you access the module that implements the template, and simply call the function directly.

Here’s an example:

#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.12"
# dependencies = [
#   "mako",
# ]
# ///

from mako.template import Template

# Construct the template, containing `foo` as a top-level module definition.
template = Template("""
<%!
def foo():
return { "extension": ".html" };
%>

<h1>Hello world!</h1>
""")
# Access the module of the template, call `foo` directly.
print(template.module.foo())
# Let's render the t...

Similar Posts

Loading similar posts...

Keyboard Shortcuts

Navigation
Next / previous item
j/k
Open post
oorEnter
Preview post
v
Post Actions
Love post
a
Like post
l
Dislike post
d
Undo reaction
u
Recommendations
Add interest / feed
Enter
Not interested
x
Go to
Home
gh
Interests
gi
Feeds
gf
Likes
gl
History
gy
Changelog
gc
Settings
gs
Browse
gb
Search
/
General
Show this help
?
Submit feedback
!
Close modal / unfocus
Esc

Press ? anytime to show this help