Skip to main content
edited tags; edited title
Link
200_success
  • 145.7k
  • 22
  • 191
  • 481

A pythonic way to build/use the jinja2 environment Jinja2 template loader

Source Link
Mike
  • 184
  • 9

A pythonic way to build/use the jinja2 environment

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.