From ca144dae2ae4221c1051351e7e219ab1618e8d20 Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Tue, 20 Mar 2007 17:35:07 +0100 Subject: [PATCH] [svn] added a loader that loads templates from functions provided --HG-- branch : trunk --- jinja/loaders.py | 45 ++++++++++++++++++++++++++++++++++++++++++++- jinja/utils.py | 2 +- 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/jinja/loaders.py b/jinja/loaders.py index 6901b40..ff701a9 100644 --- a/jinja/loaders.py +++ b/jinja/loaders.py @@ -25,7 +25,8 @@ except ImportError: resource_exists = resource_string = resource_filename = None -__all__ = ['FileSystemLoader', 'PackageLoader', 'DictLoader', 'ChoiceLoader'] +__all__ = ['FileSystemLoader', 'PackageLoader', 'DictLoader', 'ChoiceLoader', + 'FunctionLoader'] def get_template_filename(searchpath, name): @@ -333,6 +334,48 @@ class PackageLoader(CachedLoaderMixin, BaseLoader): return 0 +class FunctionLoader(CachedLoaderMixin, BaseLoader): + """ + Loads templates by calling a function which has to return a string + or `None` if an error occoured. + + .. sourcecode:: python + + from jinja import Environment, FunctionLoader + + def my_load_func(template_name): + if template_name == 'foo': + return '...' + + e = Environment(loader=FunctionLoader(my_load_func)) + + Because the interface is limited there is no way to cache such + templates. Usually you should try to use a loader with a more + solid backend. + + You can pass the following keyword arguments to the loader on + initialisation: + + =================== ================================================= + ``loader_func`` Function that takes the name of the template to + load. If it returns a string or unicode object + it's used to load a template. If the return + value is None it's considered missing. + =================== ================================================= + """ + + def __init__(self, loader_func): + self.loader_func = loader_func + + def get_source(self, environment, name, parent): + rv = self.loader_func(name) + if rv is None: + raise TemplateNotFound(name) + if isinstance(rv, str): + return rv.decode(environment.template_charset) + return rv + + class DictLoader(BaseLoader): """ Load templates from a given dict: diff --git a/jinja/utils.py b/jinja/utils.py index 4646d1d..c561da7 100644 --- a/jinja/utils.py +++ b/jinja/utils.py @@ -164,7 +164,7 @@ def buffereater(f): def raise_template_exception(exception, filename, lineno, context): """ Raise an exception "in a template". Return a traceback - object. + object. This is used for runtime debugging, not compile time. """ # some traceback systems allow to skip frames __traceback_hide__ = True -- 2.26.2