Jinja

Template Loaders

Navigation

Contents

This part of the documentation explains how to use and write a template loader.

Builtin Loaders

FileSystemLoader

Loads templates from the filesystem:

from jinja import Environment, FileSystemLoader
e = Environment(loader=FileSystemLoader('templates/'))

You can pass the following keyword arguments to the loader on initialisation:

searchpath String with the path to the templates on the filesystem.
use_memcache Set this to True to enable memory caching. This is usually a good idea in production mode, but disable it during development since it won't reload template changes automatically. This only works in persistent environments like FastCGI.
memcache_size Number of template instance you want to cache. Defaults to 40.
cache_folder Set this to an existing directory to enable caching of templates on the file system. Note that this only affects templates transformed into python code. Default is None which means that caching is disabled.
auto_reload Set this to False for a slightly better performance. In that case Jinja won't check for template changes on the filesystem.

Developing Loaders

Template loaders are just normal Python classes that have to provide some functions used to load and translate templates. Here is a simple loader implementation you can use as the base for your own loader:

from os.path import join
from jinja.parser import Parser
from jinja.exceptions import TemplateNotFound

class SimpleLoader(object):
    """
    Slimmed down version of the included `FileSystemLoader`.
    """

    def __init__(self, searchpath):
        self.searchpath = searchpath

    def get_source(self, environment, name, parent):
        """
        The get_source function is unused at the moment. However, future
        versions of jinja will use this function for the debugging
        system. It also works as helper functions for `parse` and
        `load`.
        """
        filename = join(self.searchpath, name)
        if not path.exists(filename):
            raise TemplateNotFound(name)
        f = codecs.open(filename, 'r', environment.template_charset)
        try:
            return f.read()
        finally:
            f.close()

    def parse(self, environment, name, parent):
        """
        Load and parse a template and return the syntax tree.
        """
        source = self.get_source(environment, name, parent)
        return Parser(environment, source, name).parse()

    def load(self, environment, name, translator):
        """
        Parse and translate a template. Currently only translation to
        python code is possible, later Jinja versions however will
        support translating templates to javascript too.
        """
        return translator.process(environment, self.parse(environment, name, None))

Note

Once a loader is bound to an environment, you have to omit the environment argument for the public functions get_source, parse and load.