Jinja Basics

Template time!

What We Will Be Doing

We will make a site whose pages look different at different times...in other words, a dynamic, interactive, actual app!

What Have We Done Already?

We’ve built simple apps on AppEngine already. Quick review:


What’s wrong with this? (Don’t try to run it...just look at the code.)

Missing content

Think before revealing the answer. 🙂

Possible answers:

  • No separation of concerns (view and controller mixed up)
  • If we had dozens of pages, could we make sense of things?
  • What else?

Templates To The Rescue

Templates allow us to separate concerns and manage complexity.
They will also give us the power to make dynamic applications: we will be able to create pages on the fly in response to user inputs. Woah.

Code Along

STEP 1 In a new folder, create the files app.yaml, main.py, and templates/welcome.html. (Remember touch and mkdir?

touch app.yaml
touch main.py
mkdir templates
touch templates/welcome.html

STEP 2 Populate app.yaml:

Missing content
What’s new?

STEP 3 Populate templates/welcome.html. Ask questions about any new HTML elements.

Missing content

STEP 4 Open templates/welcome.html just to make sure it renders! It’s a great idea to do this before integrating these templates into AppEngine.

STEP 5 Here is gets a little crazy. We’re going to populate main.py, and we’ll be adding code that no one really memorizes. You can find it in the official docs. Type it in (or copy-paste) and we’ll discuss it briefly.

Missing content

STEP 6 Test what we have so far!

$ dev_appserver.py app.yaml

and go to localhost:8080 in your browser.

Make sure things work. What have we done? What haven’t we done? What do you think we should do next?

STEP 7 Make a template that will display our fortune. Now we get to see why templates are called templates! Our fortune will be different at different times! The server (controller) will fill part of the template in. Create the file templates/fortune.html and populate it like so:

Missing content
Now open that file directly. Why did you see what you saw?

STEP 8 The server is going to need to render this template with the right data. In the interest of time, we’re just going to go straight to the answer, but we’ll discuss what’s going on. Update main.py as follows: Missing content

What’s new?

STEP 9 And finally we have to get our welcome page to submit the form data to the server. Details are in the curriculum, but ask questions! Missing content

STEP 10 Test, test, test.

Your Turn

Some ideas for enhancements:

For the security-minded folks: Try entering your name as <script>alert(1)</script>. Did your XSS attack work? Why do you think it did or did not?


We’ve covered:

  • Why we need templates
  • How to use Jinja templates in AppEngine
  • Passing values to templates