Templatetags on App Engine
Posted on September 25th, 2008 in Google, Programming |
Making templatetags on App Engine is a bit different from the real django. Here is how i made mine.
* Create a templatetags folder under your root folder
* Create a empty file named __init__.py
* Create your templatetags file, for this example we will use ads_manager.py
Open your ads_manager.py and enter the following code
from google.appengine.ext.webapp import template
register = template.create_template_register()
def checkShowAds(remote_add):
if remote_add == "127.0.0.1":
return ""
else:
return "ADS HERE"
register.filter("checkShowAds",checkShowAds)
from google.appengine.ext.webapp import template
– means import the template class from the package google…
register = template.create_template_register()
– register this template or something like that
def checkShowAds(remote_add):……………..
– our function
register.filter(”checkShowAds”,checkShowAds)
– add our function as custom filter
Next stop is to open your python file that you will use this templatetags/filter
and insert the following code
from google.appengine.ext.webapp import template
template.register_template_library('templatetags.ads_manager')
class MainPage(webapp.RequestHandler):
def get(self):
template_values = {
'remote_add': self.request.remote_addr
}
directory = os.path.dirname(__file__)
path = os.path.join(directory,os.path.join('templates','index.html'))
self.response.out.write(template.render(path,template_values))
template.register_template_library(’templatetags.ads_manager’)
– What this do is that it register your templatetags so you can use it on your template/view.
class MainPage(webapp.RequestHandler):……
– This and the rest of the code will just render your template while passing the remote address as ‘remote_add’ variable
Next is to open your template and add the following:
{{ remote_add|checkShowAds }}
I hope this helps. It took me days to understand the basic concept of how templatetags on app engine works.













One Response
[...] In app engine you might want to get the server information like the hostname, current url and so on, currently you can do this by passing the self.request to the template values, and from template to your filter. What if you don’t want to pass the request variable everytime? Here is a how i did it (i’m not a python guy so if i did something wrong do comment thanks) (Here is the Tutorial on templatetags) [...]