[HOW-TO] Use the Jinja2 template engine with AppEngine

410

If you're like me, then you dislike mixing programming with markup. So, naturally, you want to take the HTML that you use to generate your web page out of your Python code and into a template document. Well, AppEngine comes with a templating engine that can help you do just that!

Jinja2

Jinja2 is a powerful templating engine modeled after Django's templating system. The idea is to separate your logic from your presentation, and make your code clean and well-defined in the process.

Here's the basic process to get it working in AppEngine.

Step 1: Modify app.yaml

Open app.yaml from your AppEngine project directory in the editor of your choice. You need to do a few things here: 1) change the runtime attribute to python27, 2) add threadsafe: true, and 3) add the Jinja2 library in the configuration. Here's what your app.yaml might look like after you're done:

application: foobar
version: 1
runtime: python27
api_version: 1
threadsafe: true

libraries:
- name: jinja2
  version: latest

handlers:
- url: /.*
  script: main.app

The important bit is the libraries section - that's where you grant access to Jinja2.

Step 2: Move your HTML to a separate file

For the sake of this example, let's create a directory in your project folder called templates. Place your HTML code into a file called, let's say, index.html, underneath your templates folder.

Note: do not add a static_dir URL handler in your app.yaml file. A static_dir handler is used to expose a directory of files to the client - things like images, static JavaScript files, stylesheets, etc. It turns out that AppEngine stores these files in a separate location than your app files, for efficiency reasons. This means that if you unintentionally set, say, your templates directory as a static_dir, then your app will throw an error every time you try to use a template, because the files won't be accessible!

Now, you have to add template placeholders to your HTML. Jinja2 has a default (and quite rich) syntax that it uses to generate filled-in HTML from your templates. Here's a simple example:

<!DOCTYPE html>
<html>
    <head>
        <title>Look Ma, I'm using Jinja!</title>
    </head>
    <body>
        Hi there - I'm {{ name }}, and I {{ verb }} programming!
    </body>
</html>

The placeholders {{ name }} and {{ verb }} are what Jinja2 replaces with the data that your app provides. Remember these names - you'll have to use them when you send data to the templating engine. Almost done!

Step 3: Modify your main Python script to use Jinja2

Obviously, if you haven't already, remove the form = """<html... stuff from your Python file - that's what the template is for.

Now we must import the jinja2 module, and create an "environment" using which we can access the templating functions. Here's what the top section of your script might look like:

import os
import webapp2

import jinja2

jinja_environment = jinja2.Environment(autoescape=True,
    loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))

A few things to note here: the jinja2.Environment object that we're instantiating takes a loader argument, which takes a directory from which it can load templates; we've imported the os module just so that we can use its path manipulation functions to get the path to our templates directory. Notice also that we've used the autoescape=True argument - this makes Jinja2 escape all dangerous strings for us, so we don't have to!

Finally, to use the template in one of our request handlers, use something like this:

class MainPage(webapp2.RequestHandler):
    def get(self):
        template_values = {
            'name': 'SomeGuy',
            'verb': 'extremely enjoy'
        }

        template = jinja_environment.get_template('index.html')
        self.response.out.write(template.render(template_values))

First we create a dictionary with the name/value pairs for the template - notice that the keys are the same as those included in the template. Then we retrieve a template object using jinja_environment.get_template, and finally we render and write out the resulting HTML using template.render(template_values).

And that's it! Try it out!

asked 27 Apr '12, 21:55

Zaven%20Muradyan-1's gravatar image

Zaven Murady...
11.3k63359

accept rate: 79%

edited 30 Apr '12, 20:50

3

Very helpful, thanks!

(30 Apr '12, 23:07)

Timothy Gaweco

Timothy%20Gaweco's gravatar image

Thanks dude it was really helpful...I had been pulling my hair off reading the docs at jinja2 docs...Just tell me one more thing...The jinja template is already iinstalled in app engine ???
why dont we have to install it??

(01 May '12, 13:30)

rohit

rohit's gravatar image
8

@rohit: Yes, Jinja2 is packaged with AppEngine, so you don't have to manually install it. You just have to declare that you want to use it in your app.yaml

(01 May '12, 15:15)

Zaven Murady...

Zaven%20Muradyan-1's gravatar image

Thank you, @voithos. [Couldn't figure out how to add a link to your name in this comment....]

(01 May '12, 15:33)

John Horan

John%20Horan's gravatar image

(Never mind, looks like I did!)

(01 May '12, 15:34)

John Horan

John%20Horan's gravatar image

Thanks a lot!

(01 May '12, 17:03)

Zhadan Andrew

Zhadan%20Andrew's gravatar image

very helpful

(02 May '12, 22:12)

Serge M

Serge%20M's gravatar image

How do I link the main.app to a main.py?

(02 May '12, 23:19)

shawn casey

shawn%20casey's gravatar image

Thanks buddy this was very helpful... would suggest to append with CSS usage also

(02 May '12, 23:28)

Kiran Ajbani

Kiran%20Ajbani's gravatar image

Thank you so much for the pain free tutorial. You saved my day. I would vote you a 100 times it was possible.

(03 May '12, 10:45)

Dinesh M-2

Dinesh%20M-2's gravatar image

Awesome, Thanks for this. It worked like a charm.

(03 May '12, 14:13)

intaglioman

intaglioman's gravatar image

Thank you very much

(05 May '12, 08:13)

David Bielen

David%20Bielen's gravatar image

very helpful indeed!!

(05 May '12, 08:42)

rusydan muslih

rusydan%20muslih's gravatar image

Thanks a lot!! :)

(30 May '12, 08:03)

Tejas Pramod...

Tejas%20Pramod%20Bubane's gravatar image

You are awesome.

(15 Jul '12, 22:08)

Jason Sanchez

Jason%20Sanchez's gravatar image

thanks man....... i love educators like you........ clear stated every step as required...... thanks

(13 Sep '12, 20:32)

rakib

rakib's gravatar image

thanks so much for this great explanation. My app is converted to using jinja templates.

(05 Dec '12, 19:38)

Chris Bell

Chris%20Bell's gravatar image

I think your answer should be added to the official notes on using jinja

(12 Sep '13, 12:33)

Sriharsha-3

Sriharsha-3's gravatar image

what if i have a placeholder that has an apostrophe? how would i escape it in the python file

(08 Oct '13, 03:13)

Derp

Derp's gravatar image
showing 10 of 19 show 9 more comments

43 Answers:

12345next »

-1

I still find this confusing, as I can't get past first base! I go to google appengine: https://developers.google.com/appengine/ I am signed in.

"Open app.yaml from your AppEngine project directory in the editor of your choice"
Q1) Where is the link to get to project directory from the page I am on?! There are a multitude of links, none of which seem to say 'project directory'.

link

answered 28 Jan, 10:36

adam-35's gravatar image

adam-35
3495

-1

Where is the project directory on google's appengine website?! Can't get past first base :-(

link

answered 28 Jan, 10:34

adam-35's gravatar image

adam-35
3495

-1

Where is the project directory on google's appengine website?! Can't get past first base :-(

link

answered 28 Jan, 10:34

adam-35's gravatar image

adam-35
3495

-1

Where is the project directory on google's appengine website?! Can't get past first base :-(

link

answered 28 Jan, 10:34

adam-35's gravatar image

adam-35
3495

-1

I still find this confusing, as I can't get past first base! I go to google appengine: https://developers.google.com/appengine/ I am signed in.

"Open app.yaml from your AppEngine project directory in the editor of your choice"
Q1) Where is the link to get to project directory from the page I am on?! There are a multitude of links, none of which seem to say 'project directory'.

link

answered 28 Jan, 10:32

adam-35's gravatar image

adam-35
3495

-1

I still find this confusing, as I can't get past first base! I go to google appengine: https://developers.google.com/appengine/ I am signed in.

"Open app.yaml from your AppEngine project directory in the editor of your choice"
Q1) Where is the link to get to project directory from the page I am on?! There are a multitude of links, none of which seem to say 'project directory'.

link

answered 28 Jan, 10:32

adam-35's gravatar image

adam-35
3495

-1

I still find this confusing, as I can't get past first base! I go to google appengine: https://developers.google.com/appengine/ I am signed in.

"Open app.yaml from your AppEngine project directory in the editor of your choice"
Q1) Where is the link to get to project directory from the page I am on?! There are a multitude of links, none of which seem to say 'project directory'.

link

answered 28 Jan, 10:32

adam-35's gravatar image

adam-35
3495

-1

I still find this confusing, as I can't get past first base! I go to google appengine: https://developers.google.com/appengine/ I am signed in.

"Open app.yaml from your AppEngine project directory in the editor of your choice"
Q1) Where is the link to get to project directory from the page I am on?! There are a multitude of links, none of which seem to say 'project directory'.

link

answered 28 Jan, 10:32

adam-35's gravatar image

adam-35
3495

-1

I still find this confusing, as I can't get past first base! I go to google appengine: https://developers.google.com/appengine/ I am signed in.

"Open app.yaml from your AppEngine project directory in the editor of your choice"
Q1) Where is the link to get to project directory from the page I am on?! There are a multitude of links, none of which seem to say 'project directory'.

link

answered 28 Jan, 10:32

adam-35's gravatar image

adam-35
3495

-1

I still find this confusing, as I can't get past first base! I go to google appengine: https://developers.google.com/appengine/ I am signed in.

"Open app.yaml from your AppEngine project directory in the editor of your choice"
Q1) Where is the link to get to project directory from the page I am on?! There are a multitude of links, none of which seem to say 'project directory'.

link

answered 28 Jan, 10:32

adam-35's gravatar image

adam-35
3495

Your answer
Question text:

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "Title")
  • image?![alt text](/path/img.jpg "Title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Tags

×13,560
×9,082
×594
×192
×130
×32
×31

Asked: 27 Apr '12, 21:55

Seen: 20,183 times

Last updated: 28 Jan, 10:36