Chapter 6. Templates

Although it is possible to generate all of the HTML of your application from within strings in Python, this is generally a poor way to author HTML. In particular, it means that every time you want to change a bit of the generated HTML, you need to dig through the program, find the strings, and then change the HTML code:

formstring = '''<form method="post" action="/">
<p>Enter Guess: <input type="text" name="guess"/></p>
<p><input type="submit"></p>
</form>'''

At the same time, our web application needs to have some parts of the web pages be generated dynamically as part of the code of the web application—either based on the user’s input or based on some information retrieved from the Datastore.

The compromise that solves both problems is a template. A template is a file that contains mostly HTML with specially marked areas of the template that are replaced by data passed into the template from the Python code when the template is rendered.

There are many different template languages and syntaxes. The default template syntax used by Google App Engine is borrowed from the Django project (http://www.djangoproject.com).

Template Syntax

The template syntax in Google App Engine augments the HTML by using curly braces to identify where we are giving commands to the template system. The template for our number-guessing program when we are responding to a GET request is in the file index.htm:

<p>{{ hint }}</p> <form method="post" action="/"> <p>Enter Guess: <input type="text" ...

Get Using Google App Engine now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.