Mako is a high-performance Python template library combining fast execution with familiar Python syntax and template inheritance.
Basic Syntax & Expressions
Variable x: ${x}
Expression arithmetic: ${x + 1}
HTML-escaped filter: ${x | h}
URL-encoded filter: ${x | u}
Trimmed whitespace: ${x | trim}
Control Structures
Control statements begin with % and must be terminated with % endif, % endfor, etc.:
% for user in users:
% if user.is_active:
<li>${user.name} (Active)</li>
% else:
<li>${user.name} (Inactive)</li>
% endif
% endfor
Embedded Python Code
Render-Time Python Blocks
<%
greeting = "Hello, " + user.name.upper()
total_score = sum(user.scores)
%>
<p>${greeting}: ${total_score}</p>
Module-Level Python Blocks
The <%! ... %> tag executes once at the module level when the template is compiled into Python code:
<%!
import datetime
def format_date(dt):
return dt.strftime("%Y-%m-%d")
%>
<p>Today: ${format_date(datetime.date.today())}</p>
Defs (Macros) & Raw Blocks
<%def name="render_card(title, body)">
<div class="card">
<h3>${title}</h3>
<p>${body}</p>
</div>
</%def>
${render_card("Feature", "Card body text")}
<%text filter="h">
This is a raw block where ${expressions are not evaluated}.
</%text>
<%doc>
Multi-line template comment
</%doc>
Template Inheritance
Base Template (base.html)
<!doctype html>
<html>
<head>
<title><%block name="title">Default Title</%block></title>
</head>
<body>
<header><h1><%block name="header" /></h1></header>
<main>${self.body()}</main>
</body>
</html>
Child Template (child.html)
<%inherit file="base.html" />
<%block name="title">Page Title</%block>
<%block name="header">Welcome to my site</%block>
<p>This is the main body content injected into self.body().</p>
Python API Usage
from mako.template import Template
template = Template("Hello, ${name}!")
print(template.render(name="World"))