I’am using Python 2.5 on App Engine and tried to get the Jinja2 ModuleLoader to work.
To initialize the environment I use :
@staticmethod # get Jinja environment (global)
def get_new(): # and initialize Jinja environment
if myEnv._my_env == None :
path = os.path.join(os.path.dirname(__file__), 'compiled')
myEnv._my_env = Environment(loader = ModuleLoader(path))
return myEnv._my_env
‘compiled’ is a directory in my GAE project.
But I receive TemplateNotFound exceptions all the time??
I compiled the templates using :
env = Environment(extensions=['jinja2.ext.i18n'])
env.filters['euros'] = Euros
db_runtimes = Runtimes.all() # the html templates saved in a db.Blob
for each in db_runtimes.fetch(999) :
key = each.key().name()
source = db.Blob(each.content).decode('utf-8')
name = key.split('.')[0]
raw = env.compile(source, name=name, filename=name + '.py', raw=True)
each.compiled = db.Blob(raw.encode('utf-8')) # compile and save the .py
each.put()
The resulting code looks fine. Any ideas?
I hope you can help me. This article from Rodrigo Moraes shows that loading templates from python modules is very fast. But in this 2009 proof of concept he “hacked” the Jinja code to be able to run the code. I think the ModuleLoader should do the same job.
https://groups.google.com/group/pocoo-libs/browse_thread/thread/748b0d2024f88f64
The testmod.py looks like this :
from __future__ import division
from jinja2.runtime import LoopContext, TemplateReference, Macro, Markup, TemplateRuntimeError, missing, concat, escape, markup_join, unicode_join, to_string, identity, TemplateNotFound
name = u'testmod.py'
def root(context, environment=environment):
if 0: yield None
yield u'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"\n"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n<html xmlns="http://www.w3.org/1999/xhtml">\n<head>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />\n<title>TEST</title>\n</head>\n<body>\n\t<p>test template</p>\n</body>\n</html>'
blocks = {}
debug_info = ''
And the page handler :
def get(self):
my_env = myEnv.get()
page = 'testmod.py'
template = my_env.get_template(page)
self.response.out.write(template.render({}))
I’have also tried to get the template without the .py extension.
Update: See this Gist with the code I use for a CMS:
https://gist.github.com/voscausa/9154936
Update : Now I am using Python 27 and was able to create a module loader, which can load jinja compiled templates (python code) from a package or from the database (package = None).
To initialize the loader, you can use: