今回はGoogle App Engineでテンプレートエンジンjinja2を使用してみます。
まずはHTMLのテンプレートを用意します。
ポイントは9行目の”{{ name }}“です。
ここの所にPythonのプログラムで値を指定します。
作成したテンプレートファイルは、アプリケーションの格納フォルダ(app.yami等があるところ)に置いておきます。
■template.html
1 2 3 4 5 6 7 8 9 10 11 | <! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> < html lang = "ja" > < head > < meta http-equiv = "Content-Type" content = "text/html; charset=utf-8" > < title >私のホームページ</ title > </ head > < body > < h1 >私のホームページです</ h1 > {{ name }} </ body > </ html > |
.renderメソッドでnameに値をセットしてやります(8行目)
■main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #coding: UTF-8 import webapp2 from jinja2 import Template, Environment, FileSystemLoader class MainHandler(webapp2.RequestHandler): def get( self ): self .response.write(tmpl.render(name = u '山田太郎' )) tmpldir = '.' env = Environment(loader = FileSystemLoader(tmpldir, encoding = 'utf8' ), autoescape = False ) tmpl = env.get_template( 'template.html' ) app = webapp2.WSGIApplication([( '/' , MainHandler)], debug = True ) |
実行すると、”山田太郎”という文字列がテンプレートに埋め込まれて表示されます。