20 January, 2010

Using the Templates from Python

from google.appengine.ext.webapp import template

class MainHandler(webapp.RequestHandler):
  def get(self):
      temp = os.path.join(
              os.path.dirname(__file__),
             'templates/index.htm')
      outstr = template.render(
              temp,
             {'hint': 'Good luck!'})
             self.response.out.write(outstr)
We add an import statement to make the template library available to our application.

Within the get() method, the first line looks up the full path to the template file by using the path to the currently executing file and adding templates/index.htm to the end of the current file’s path.

The actual template processing is done in the template.render() line. This takes two parameters: the first is the location of the template file from the previous step (stored in the variable temp) and the second is a Python dictionary object, which contains the strings to be placed in the template where the {{ hint }} entries are found. The results f the substitution of the variables into the template are returned as a string in the variable outstr.

No comments: