Mako テンプレートエンジンを使ってみる
PythonでHTMLテキストを作る必要があって、ネットで調べたら Mako というテンプレートエンジンがあった。Makoって聞くと頭の中で「マコ」になって、日本語的な音の響きを感じてしまうが、作者は日本人ではなさそうだ。python.orgのサイトでも使われていて実績もある。
そんなことで、自分の場合は単純な置き換え程度にしか使わない(使える頭がない)けど、忘れないためのメモとしてサンプルを残しておく。
実験環境
- Ubuntu 9.10
- Python 2.6.4
Makoのインストール
最新バージョンは 0.3.2 だが、Ubuntuなのでパッケージをインストールする。
$sudo apt-get install python-mako
HTMLテンプレートファイルを読んでHTMLを出力する
#!/usr/bin/python
#coding:utf-8
from mako.template import Template
t = Template(filename="./test.tmpl",
input_encoding="utf-8",
output_encoding="utf-8",
encoding_errors="replace")
name_list = ['John','Paul','George','Ringo']
d = {'artist': 'Beatles', 'member': name_list}
html_out = t.render(**d)
print html_out
HTMLテンプレートファイル test.tmpl
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>mako test</title>
</head>
<body>
<h1>${artist}</h1>
<p>メンバーは ${len(member)} 人です</p>
<ul>
% for item in member:
<li>${item}</li>
% endfor
</ul>
</body>
</html>
出力したHTMLファイル
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>mako test</title> </head> <body> <h1>Beatles</h1> <p>メンバーは 4 人です</p> <ul> <li>John</li> <li>Paul</li> <li>George</li> <li>Ringo</li> </ul> </body> </html>
