Google App EngineでMakoを使う

Google App EngineでテンプレートエンジンMakoを使う方法……といっても、特別なことは何も必要ない。アーカイブを展開してできた mako ディレクトリをアプリケーションディレクトリにコピーすれば使えるようになる。

日本語を使う場合の注意点についてはこちらを参照のこと。GAEではRequestもResponseもDatastoreもUnicodeに対応しているので、あまり神経質にならなくても大丈夫。

コード例

  • テンプレートファイルは views/ ディレクトリに置く
  • デフォルトの拡張子は .html
  • エンコーディングは utf-8 固定

次のようなベースクラスを用意しておく。

from mako.template import Template
from mako.lookup import TemplateLookup
 
class RequestHandler(webapp.RequestHandler):
    viewDir = os.path.join(os.path.dirname(__file__), "views")
    lookup = TemplateLookup(directories=[viewDir], input_encoding='utf-8')
 
    def render(self, view, vars={}, type=".html"):
        tmpl = self.lookup.get_template(view + type)
        return tmpl.render_unicode(**vars)
 
    def display(self, *args, **named):
        self.response.out.write(self.render(*args, **named))

サブクラスでは display または render メソッドでレンダリングを行う。

class MainPage(RequestHandler):
    def get(self):
        self.display('index', {"var": "value"})

One Response

  1. [...] This post was mentioned on Twitter by Takayuki Miwa. Takayuki Miwa said: ブログ更新: Google App EngineでMakoを使う http://bit.ly/dhZK33 [...]

Leave a Reply