Skip to content

Jinja2 templates on GAE

App Engine

After two entrances about Google App Engine with Python, let’s go further, and now it’s time to start with HTML templates. This is the right way of using HTML templates and avoid mixing HTML and Python (the opposite as programming Classic ASP, all mixed in one file!). I will be using the Jinja2 template engine on GAE, that are very useful, and in some manner, similar to the templates used with HandleBars in Javascript, although the differences are important when using complex features.

Using HTML templates for jinja2

Although the examples you have seen heer are very cool (well, you know …. good examples! ;–), the truth is that including HTML code inside Python is not a very handy solution, and the best way to proceed is using HTML templates, so let’s try jinja2, who’s documentation is here: http://jinja.pocoo.org/docs/intro/#.

Before starts, the best way of using templates is to follow the instructions from Google Developers: https://developers.google.com/appengine/docs/python/gettingstartedpython27/templates.

Fist, you need to include the library in app.yaml:, and write that we want to use jinja2, latest version:

- name: jinja2
  version: latest

Next, on Python, you need to create an environment to rescue the templates, like this:

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)

Time to moe to HTML and write a template, that it will be the content on the html variable from the previous example, and we save it as formulario.html::


<html lang="es">
<head>
<meta charset="utf-8"/>
<title>Form Example</title>
</head>
<body>
<h1>Probando Jinja2 en GAE - Manejandodatos.es</h1>

<p>{{message}}</p>
<form method="post">
<label for="firstName">Name:</label>
<input name="firstName" type="text" value="{{nombre}}"/><br />
<input name="" type="submit" value="Save"/>
</form>
</body>
</html>

Y para hacer uso de una plantilla, la rescato del “ambiente”, y la digo que la muestre:


def get(self):
tem_values = { 'message': 'Probando' }
template = JINJA_ENVIRONMENT.get_template('formulario.html')
self.response.write(template.render(tem_values))

Because in the template you have used {{variable}}, it’s compulsory to send a dictionary to the template, with the values. This way, the result will be:

Probando plantillas jinja2

Testing templates on  jinja2

Using a “base” template

One of the best things you can do before continue is creating a “base” template, with the desing of our website, And for that, one good option is trying layoutit.com, where you can design websites using Twitter Bootstrap, and once created visually, you can download all the HTML, CSS and Javascript code. I have created an easy template, although later on, i have introduced a few modifications for adjusting it to this example. The final aspect is this: (remember that you are viewing an static file!):

 

Plantilla Manejando datos

Using a template

The file base.html will be located under the templates directory, while the rest of the files like CSS, Javascript, images, … are located on several directories too, trying to have a clean structure. Of course, when you starts the application, you will have:

Usando una plantilla

Using a template

As you can verify, no static files are loaded, so we need to modify the app.yaml file and specify that static directory has static content.


application: templates
version: 1
runtime: python27
api_version: 1
threadsafe: yes

handlers:
- url: /favicon\.ico
static_files: favicon.ico
upload: favicon\.ico

- url: /static
static_dir: static

- url: .*
script: ejemplo_plantilla.app

libraries:
- name: webapp2
version: "2.5.2"
- name: jinja2
version: latest

Of course, you need to modify base.html template as weell, and rename css/ to /static/css/, (you need to do that again for the dirs img y js). Once finished, reload the page, and out page is correct, now from the server:

 

Plantilla funcionando desde el servidor

Template used by the GAE server

You can download the template here gae_plantilla_manejandodatos, and the full project gae_ejemplo_templates.

And … that’s all by now! Happy coding!

Manejando Datos Newsletter

Noticias, entradas, eventos, cursos, … News, entrances, events, courses, …


Gracias por unirte a la newsletter. Thanks for joining the newsletter.