I originally implemented Jinja2 on App Engine using the examples shown on the App Engine site here: https://developers.google.com/appengine/docs/python/gettingstartedpython27/templates where jinja2 is imported directly:
import jinja2
import os
jinja_environment = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
class MainPage(webapp2.RequestHandler):
def get(self):
greetings = 'somestring'
template_values = {
'greetings': greetings,
}
template = jinja_environment.get_template('index.html')
self.response.out.write(template.render(template_values))
But I’m currently bolting on Simpleauth (https://github.com/crhym3/simpleauth) which follows the implementation that Nick Johnson described here: http://blog.notdot.net/2011/11/Migrating-to-Python-2-7-part-2-Webapp-and-templates where jinja2 is imported from webapp2_extras:
import os
import webapp2
from webapp2_extras import jinja2
class BaseHandler(webapp2.RequestHandler):
@webapp2.cached_property
def jinja2(self):
return jinja2.get_jinja2(app=self.app)
def render_template(self, filename, **template_args):
self.response.write(self.jinja2.render_template(filename, **template_args))
class IndexHandler(BaseHandler):
def get(self):
self.render_template('index.html', name=self.request.get('name'))
Which of these is the preferred method for using jinja2? (They don’t seem to play together nicely, and would prefer to standardize on the best option.)
I guess they are pretty much the same. What webapp2_extras.jinja2 does in addition is that it caches jinja2.Environment() initialization (for the request duration). Plus, you can leverage config/registry system of the webapp2.
Looking at get_jinja2() source you’ll see that it’s just a handy wrapper for jinja2.Environment() with some default environment args and enabled extensions (e.g. i18n).