Global Template System in Google App Engine

I love using one template file that includes my content. I personally don’t like the idea of having to include “header” and “footer” into every single content file.

My main reason is because sometime I have multiple templates (for example, view, mobile, json or xml). If I include the template into my content, I will need some logic to cater for different views. Therefore, I did some research and managed to come up with something relatively simple.

This is how basic Google App Engine Template works (more information visit: Using Templates)

import os
from google.appengine.ext.webapp import template

class MainPage(webapp.RequestHandler):
  def get(self):
    template_values = {'content' : 'hello world'}
    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

This is how I get what I need to work

import os
from google.appengine.ext.webapp import template

class MyTemplate(webapp.RequestHandler):
  def render(self, template_name, param):
    template_values = dict({'template_name': template_name}, ** param)
    path = os.path.join(os.path.dirname(__file__) + '/view', 'my_template.html')
    self.response.out.write(template.render(path, template_values))

class MainPage(MyTemplate): # extend MyTemplate
  def get(self):
    template_values = {'content' : 'hello world'}
    # calls render function from super class (MyTemplate)
    self.render('index.html', template_values)

Simple?

How to merge 2 dictionaries in Python

I have been disappearing for quite awhile due to work and other stuff. Recently, I have been looking heavily into Google App Engine (GAE) and Python. Hopefully, I will discover something interesting and is able to share them here.

Today I was creating a global template system in GAE and I found myself needing to merge 2 dictionaries together.

I thought it was gonna be something like merge or append functions but Stackoverflow points me to this interesting syntax.

a = { ‘one’ : ‘one’, ‘two’ : ‘two’}

b = {‘three’ : ‘three’}

c = dict(a, ** b) # merge a and b

I questioned myself about the syntax for awhile but I agreed to try it and it works perfectly.