Mako は、高速な実行性能と親しみやすい Python 構文、テンプレート継承機能を兼ね備えた高機能 Python テンプレートライブラリです。
基本構文と式展開
Variable x: ${x}
Expression arithmetic: ${x + 1}
HTML-escaped filter: ${x | h}
URL-encoded filter: ${x | u}
Trimmed whitespace: ${x | trim}
制御構造
制御文は % で始まり、% endif や % endfor などで終了する必要があります:
% for user in users:
% if user.is_active:
<li>${user.name} (Active)</li>
% else:
<li>${user.name} (Inactive)</li>
% endif
% endfor
埋め込み Python コード
描画時 (Render-Time) Python ブロック
<%
greeting = "Hello, " + user.name.upper()
total_score = sum(user.scores)
%>
<p>${greeting}: ${total_score}</p>
モジュールレベル (Module-Level) Python ブロック
<%! ... %> タグは、テンプレートが Python コードにコンパイルされる際にモジュールレベルで一度だけ実行されます:
<%!
import datetime
def format_date(dt):
return dt.strftime("%Y-%m-%d")
%>
<p>Today: ${format_date(datetime.date.today())}</p>
Defs (マクロ) と生テキストブロック
<%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>
テンプレート継承
ベーステンプレート (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.html)
<%inherit file="base.html" />
<%block name="title">Page Title</%block>
<%block name="header">Welcome to my site</%block>
<p>これは self.body() に挿入される本文コンテンツです。</p>
Python API の利用法
from mako.template import Template
template = Template("Hello, ${name}!")
print(template.render(name="World"))