開発したアプリなど一覧

Mako Templates for Python

アフィリエイトリンクを含む場合があります

Pythonのテンプレートエンジンで何がいいかなーと思って、とりあえずだが速いと評判の Mako を使用してみる。日本語の資料がほとんどないが、サンプルソースがあったのでどうにかなるだろう。

インストール

easy_install を使うと楽。ez_setup.py をダウンロードし、実行する。その後

$ easy_install Mako

とすると Mako のインストールが完了する。楽すぐる。

基本

>>> from mako.template import Template >>> mytemplate = Template("hello world!") >>> print mytemplate.render() hello world!

変数を使用する。Template.render()の引数に変数を渡してやる。

>>> from mako.template import Template >>> mytemplate = Template("hello, ${name}!") >>> print mytemplate.render(name="jack") hello, jack!

ループとif文 構文は単純

>>> from mako.template import Template >>> text = """ ... % for a in t_list : ... % if a[0] == 't' : ... its two or three ... % elif a[0] == 'f' : ... four / five ... % else : ... one ... % endif ... % endfor ... """ >>> conv = {'t_list' : ['one', 'two', 'three', 'four', 'five']} >>> mytemplate = Template(text) >>> print mytemplate.render(**conv)

one its two or three its two or three four / five four / five

テンプレートファイルを読み込む。

$ cat > docs/fuga.txt this is fuga.txt

$ python >>> from mako.template import Template >>> mytemplate = Template(filename='./docs/fuga.txt') >>> print mytemplate.render() this is fuga.txt

Templateオブジェクトを生成時に、module_dirctory を指定すると、次回からはキャッシュを使用して高速化する。(という認識でいいのかな・・?)

>>> from mako.template import Template >>> mytemplate = Template(filename='/docs/fuga.txt', module_directory='/tmp/mako_modules') >>> print mytemplate.render() this is fuga.txt

TemplateLookup を使用すると、読み込むファイルのディレクトリを指定できる。<%include file=''/> はファイルを読み込む関数みたいなもん。

>>> from mako.template import Template >>> from mako.lookup import TemplateLookup >>> mylookup = TemplateLookup(directories=['/docs']) >>> mytemplate = Template("""<%include file="fuga.txt"/> hello world!""", lookup=mylookup) this is fuga.txt hello world!

Unicodeの処理。別にこんなことしなくても日本語使えるのだが一応。

$ cat > docs/unicode.txt ゆにこーどてすと

$ python >>> from mako.template import Template >>> from mako.lookup import TemplateLookup >>> mylookup = TemplateLookup(directories=['./docs'], output_encoding='utf-8', encoding_errors='replace') >>> mytemplate = mylookup.get_template("unicode.txt") >>> print mytemplate.render() ゆにこーどてすと

例外処理 import exceptions して try 文書けば ok かの

>>> from mako import exceptions >>> try: ... template = lookup.get_template(uri) ... print template.render() ... except: ... print exceptions.text_error_template().render() ... Traceback (most recent call last): File "", line 2, in None NameError: name 'lookup' is not defined

とりあえずはこのへんがわかればテンプレートとして使う分には十分かな。というわけで終了。

Sponsored Link

コメント

タイトルとURLをコピーしました