Global Template System in Google App Engine
January 9, 2011 1 Comment
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?