| ================ |
| Template Loaders |
| ================ |
| |
| This part of the documentation explains how to use and write a template loader. |
| |
| Builtin Loaders |
| =============== |
| |
| [[list_of_loaders]] |
| |
| Developing Loaders |
| ================== |
| |
| Template loaders are just normal Python classes that have to provide some |
| functions used to load and translate templates. |
| |
| Because some of the tasks a loader has to do are redundant there are mixin |
| classes that make loader development easier. |
| |
| Here the implementation of a simple loader based on the `LoaderMixin` from |
| `jinja.loaders`: |
| |
| .. sourcecode:: python |
| |
| import codecs |
| from os.path import join |
| from jinja.loaders import LoaderMixin |
| from jinja.exceptions import TemplateNotFound |
| |
| class SimpleLoader(LoaderMixin): |
| |
| def __init__(self, path): |
| self.path = path |
| |
| def get_source(self, environment, name, parent): |
| filename = join(self.path, name) |
| if not path.exists(filename): |
| raise TemplateNotFound(name) |
| f = codecs.open(filename, 'r', environment.template_charset) |
| try: |
| return f.read() |
| finally: |
| f.close() |
| |
| The functions `load` and `parse` which are a requirement for a loader are |
| added automatically by the `LoaderMixin`. |
| |
| Additionally to the `LoaderMixin` there is a second mixin called |
| `CachedLoaderMixin` that implements memory and disk caching of templates. |
| |
| It works basically the same, just that there are two more things to implement: |
| |
| .. sourcecode:: python |
| |
| import codecs |
| from os.path import join, getmtime |
| from jinja.loaders import CachedLoaderMixin |
| from jinja.exceptions import TemplateNotFound |
| |
| class CachedLoader(CachedLoaderMixin): |
| |
| def __init__(self, path): |
| self.path = path |
| CachedLoaderMixin.__init__( |
| True, # use memory caching |
| 40, # for up to 40 templates |
| '/tmp', # additionally save the compiled templates in /tmp |
| True # and reload cached templates automaticall if changed |
| ) |
| |
| def get_source(self, environment, name, parent): |
| filename = join(self.path, 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 check_source_changed(self, environment, name): |
| return getmtime(join(self.path, name)) |
| |
| You don't have to provide the `check_source_changed` method. If it doesn't |
| exist the option `auto_reload` won't have an effect. |