This part of the Python Guestbook code walkthrough shows how to use Jinja templates to generate dynamic web content.
This page is part of a multi-page tutorial. To start from the beginning and see instructions for setting up, go to Creating a Guestbook.
HTML embedded in code is messy and difficult to maintain. It's better to use a templating system, where the HTML is kept in a separate file with special syntax to indicate where the data from the application appears. There are many templating systems for Python: EZT, Cheetah, ClearSilver, Quixote, Django, and Jinja2 are just a few. You can use your template engine of choice by bundling it with your application code.
For your convenience, App Engine includes the Django and Jinja2 templating engines.
Using Jinja2 Templates
The app.yaml
file lists the latest version of jinja2
as a required library.
Production applications should use an
actual version number
rather than version: latest
.
The app imports jinja2
and creates a jinja2.Environment
object.
The get
method for the MainPage
request handler forms a dictionary of
key/value pairs and passes it to template.render
.
The page is rendered according to the index.html
template, which receives
the dictionary as input.
The JINJA_ENVIRONMENT.get_template(name)
method takes the name of a template
file and returns a template object. The template.render(template_values)
call
takes a dictionary of values, and returns the rendered text. The template uses
Jinja2 templating syntax to access and iterate over the values, and can refer to
properties of those values.