Google App Engine (Python) カスタムタグを作ってみよう
Google App Engine のSDKに含まれる template.py はDjangoのテンプレートエンジンを簡単に扱えるようにラップしてくれている。これをうまく活用したい。
まずは、app.yamlから呼び出されるハンドラーでカスタムタグライブラリーを登録する。
今回は、app/template_helper.pyにカスタムタグの定義を書くことにする。app.template_helperとあるのはパッケージ名である。
main_handler.py
# -*- coding: utf-8 -*- # Google App Engine imports. from google.appengine.ext.webapp import template from google.appengine.ext.webapp import util from google.appengine.ext.webapp import WSGIApplication from app.main import main, member, signin application = WSGIApplication( main.handlers + member.handlers + signin.handlers, debug=True) def main(): template.register_template_library('app.template_helper') util.run_wsgi_app(application) if __name__ == '__main__': main()
app/template_helper.py の実装はこんな感じ。(サンプルなので役に立つことは何もしていないけど・・・)
# -*- coding: utf-8 -*- from django.template import Node, TemplateSyntaxError from google.appengine.ext.webapp import template from django import template as django_template register = template.create_template_register() class SampleTag(Node): def __init__(self, arg1): self.arg1 = arg1 def render(self, context): return self.arg1 @register.tag def sample_tag(parser, token): bits = token.split_contents() if len(bits) != 2: raise TemplateSyntaxError, "sample_tag tag takes exactly one argument" return SampleTag(bits[1])
app/template_helper.py の本当の実装方法は、Djangoのリファレンスが詳しいのでそちらを参照して下さい。
Google App Engine でカスタムタグを作る方法についてご紹介しました。