爬虫類嫌いのPython日記

爬虫類が大の苦手の筆者が、Pythonに挑戦。他にも、RubyやObjective-C、Google Appengine、Herokuなど色々とチャレンジしています。

GoogleAppEngineのテンプレートに値を受け渡す

デザインとロジックの分離が、テンプレートを使用する最大のメリットです。
main.py側に値を用意して、それをテンプレート側に渡してみましょう。

main.pyの修正

main.py

class MainHandler(webapp.RequestHandler):

  def get(self):
    text = 'hogehoge'
    date = '2010/08/03'
    list = {'text': text, 'date': date}
    fpath = os.path.join(os.path.dirname(__file__), 'templates', 'index.html')

    html = template.render(fpath, list)
    self.response.out.write(html)

テンプレートファイルの修正

templates/index.html

<body>
  <h1>Sample Page</h1>
  <div>{{text}}</div>
  <div>{{date}}</div>
</body>

値の受け渡しの仕組み

まず、受け渡す値をリストとして用意します。

text = 'hogehoge'
date = '2010/08/03'
list = {'text': text, 'date': date}

それぞれの値にラベルをつけたディクショナリを作成します。
そして、これをレンダリングする時に引数として渡すだけです。

html = template.render(fpath, list)

テンプレート側で値を受ける場所は{{}}で括った中に、表示したい値のラベルを記入するだけです。
この辺は、PHPSmartyの経験があれば違和感はないと思います。