I am playing around with building my own back end with python 2.7 and jinja2/cgi. Originally I was defining some of my environment and loader variables at the top but figured this was not the best practice. I then defined functions for each, but they'd only get called once or twice depending on which route it decided to execute. I came up with this class idea instead that I pass into my dispatch function, which in turn passes it into whatever rendering function happens to be being executed. Is this the proper 'pythonic' way to approach having a template loader, and if not would anyone have any suggestions?
class Template(object):
def __init__(self):
self._environment = None
def __call__(self, temp_name):
return self.get_env.get_template(temp_name)
@property
def get_env(self):
return self._environment
@get_env.getter
def get_env(self):
if not self._environment:
self._loader = jinja2.FileSystemLoader(searchpath=os.path.join(
os.path.dirname(os.path.abspath(__file__)), '../templates/madlib/'))
self._environment = jinja2.Environment(loader = self._loader)
return self._environment
This class then allows me to just call template('templateFileName.j2') and be returned that jinja template object. If the environment is not created, the getter will create one for me.