Makoでshift_jisのテンプレートを使って、shift_jisで出力する

welcome to Mako!
多機能だけど重くない感じ?バランス崩れてないというか。
テンプレートファイルをディレクトリ指定で探してくれるのがいい感じだし、制御構文のところが変な空行になったりしないのも素敵。
あと、名前がいい。アオザメのことなのね。

入力

shift_jisのテンプレートを読ませようとして、

In [42]: tmpl = mako.template.Template(filename='shift_jis.mako')

と書いたら、

<class 'mako.exceptions.CompileException'>: Could not read template using 
encoding of 'ascii'.  Did you forget a magic encoding comment? in file 'shift_jis.mako' at line: 0 char: 0

と教えてくれたので、Pythonのファイルと同じように

# coding: shift_jis
<html>
	<head>
		<title>${title}</title>
	</head>
	<body>
		<p>${status}</p>
		<p>${detail}</p>
%if ref:
		<p><a href="${ref}">${anchor}</a></p>
%endif
	<body>
<html>

と行頭でエンコーディングを指定してあげたらちゃんと通りました。面白い。

出力

上記のテンプレートで出力までさせたら

<type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode characters in position 238-240: ordinal not in range(128)

と教えてくれたので、

In [49]: tmpl = mako.template.Template(filename='shift_jis.mako', output_encoding='shift_jis')

として出力エンコーディングを指定。
あとは普通にできました。

In [50]: f = open('shift_jis.html', 'w')

In [51]: f.write(tmpl.render(**{'title':'hoge', 'status':'bar', 'detail':'foo', 'ref': 'piyo', 'anchor': 'fuga'}))

In [52]: f.close()

Mako偉い。
気軽なのはtemplateモジュールだけど、制御構文入れたくなったときに使おう。