GAE/Python標準付属のテンプレートエンジンであるDjangoを使ってみました。
テンプレート
以下のファイルを、 /template/index.html に保存しました。{{message}}の部分が、渡された変数に置換されます。
1 2 3 4 5 6 7 8 9 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja"> <head> <title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></title> </head> <body> {{message}} </body> </html> |
プログラム本体
プログラムはこんな感じになります。DjangoはGAEでは標準で組み込まれているので、importするだけで使えます。google.appengine.ext.webappからtemplateモジュールをインポートしましょう。
template.renderにテンプレートのPathと変数のディクショナリを渡すことで、テンプレートに変数を埋め込めます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #!/usr/bin/env python # -*- coding: utf-8 -*- import os from google.appengine.ext import webapp from google.appengine.ext.webapp import util, template class MainHandler(webapp.RequestHandler): def get(self): params = {'message':u'テンプレートエンジンで表示しています。'} fpath = os.path.join(os.path.dirname(__file__), 'templates','index.html') html = template.render(fpath, params) self.response.out.write(html) def main(): application = webapp.WSGIApplication([('/', MainHandler)], debug=True) util.run_wsgi_app(application) if __name__ == '__main__': main() |
テンプレートを適用の処理を関数にまとめるとこうなります。get関数がシンプルになりました。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #!/usr/bin/env python # -*- coding: utf-8 -*- import os from google.appengine.ext import webapp from google.appengine.ext.webapp import util, template class MainHandler(webapp.RequestHandler): def get(self): params = {'message':u'テンプレートエンジンで表示しています。'} print_with_template(self, "index.html", params) def print_with_template(self, view, params = {}): fpath = os.path.join(os.path.dirname(__file__), 'templates', view) html = template.render(fpath, params) self.response.out.write(html) def main(): application = webapp.WSGIApplication([('/', MainHandler)], debug=True) util.run_wsgi_app(application) if __name__ == '__main__': main() |
まとめ
テンプレートエンジンを使うと、ロジックとデザインを分離でき見通しのよいプログラムになります。大規模なアプリ開発には必須のテクニックです。