genshi.template.loader.TemplateLoader

Package genshi :: Package template :: Module loader :: Class TemplateLoader |

# Class TemplateLoader

    object --+
             |
            TemplateLoader

Responsible for loading templates from files on the specified search path.

    >>> import tempfile
    >>> fd, path = tempfile.mkstemp(suffix='.html', prefix='template')
    >>> os.write(fd, u'<p>$var</p>'.encode('utf-8'))
    11
    >>> os.close(fd)

The template loader accepts a list of directory paths that are then used when searching for template files, in the given order:

    >>> loader = TemplateLoader([os.path.dirname(path)])

The load() method first checks the template cache whether the requested template has already been loaded. If not, it attempts to locate the template file, and returns the corresponding Template object:

    >>> from genshi.template import MarkupTemplate
    >>> template = loader.load(os.path.basename(path))
    >>> isinstance(template, MarkupTemplate)
    True

Template instances are cached: requesting a template with the same name results in the same instance being returned:

    >>> loader.load(os.path.basename(path)) is template
    True

The auto_reload option can be used to control whether a template should be automatically reloaded when the file it was loaded from has been changed. Disable this automatic reloading to improve performance.

    >>> os.remove(path)

Instance Methods
__init__(self, search_path=None, auto_reload=False, default_encoding=None, max_cache_size=25, default_class=None, variable_lookup=`'``strict``'`, allow_exec=True, callback=None) Create the template laoder. |
__getstate__(self) |
__setstate__(self, state) |
load(self, filename, relative_to=None, cls=None, encoding=None) Load the template with the given name. |
Inherited from `object`: `__delattr__`, `__format__`, `__getattribute__`, `__hash__`, `__new__`, `__reduce__`, `__reduce_ex__`, `__repr__`, `__setattr__`, `__sizeof__`, `__str__`, `__subclasshook__`

Static Methods
`function` |
directory(path) Loader factory for loading templates from a local directory. |
`function` |
package(name, path) Loader factory for loading templates from egg package data. |
`function` |
prefixed(**delegates) Factory for a load function that delegates to other loaders depending on the prefix of the requested template path. |

Instance Variables
| auto_reload Whether templates should be reloaded when the underlying file is changed

Properties
Inherited from `object`: `__class__`

Method Details

### __init__(self, search_path=None, auto_reload=False, default_encoding=None, max_cache_size=25, default_class=None, variable_lookup=`'``strict``'`, allow_exec=True, callback=None) (Constructor) |
Create the template laoder. Parameters: `search_path` - a list of absolute path names that should be searched for template files, or a string containing a single absolute path; alternatively, any item on the list may be a ''load function'' that is passed a filename and returns a file-like object and some metadata `auto_reload` - whether to check the last modification time of template files, and reload them if they have changed `default_encoding` - the default encoding to assume when loading templates; defaults to UTF-8 `max_cache_size` - the maximum number of templates to keep in the cache `default_class` - the default Template subclass to use when instantiating templates `variable_lookup` - the variable lookup mechanism; either "strict" (the default), "lenient", or a custom lookup class `allow_exec` - whether to allow Python code blocks in templates `callback` - (optional) a callback function that is invoked after a template was initialized by this loader; the function is passed the template object as only argument. This callback can be used for example to add any desired filters to the template Overrides: object.__init__ See Also: LenientLookup, StrictLookup Note: Changed in 0.5: Added the `allow_exec` argument

### load(self, filename, relative_to=None, cls=None, encoding=None) |
Load the template with the given name. If the `filename` parameter is relative, this method searches the search path trying to locate a template matching the given name. If the file name is an absolute path, the search path is ignored. If the requested template is not found, a TemplateNotFound exception is raised. Otherwise, a Template object is returned that represents the parsed template. Template instances are cached to avoid having to parse the same template file more than once. Thus, subsequent calls of this method with the same template file name will return the same Template object (unless the `auto_reload` option is enabled and the file was changed since the last parse.) If the `relative_to` parameter is provided, the `filename` is interpreted as being relative to that path. Parameters: `filename` - the relative path of the template file to load `relative_to` - the filename of the template from which the new template is being loaded, or `None` if the template is being loaded directly `cls` - the class of the template object to instantiate `encoding` - the encoding of the template to load; defaults to the `default_encoding` of the loader instance Returns: the loaded Template instance Raises: `TemplateNotFound` - if a template with the given name could not be found

### directory(path) Static Method |
Loader factory for loading templates from a local directory. Parameters: `path` - the path to the local directory containing the templates Returns: `function` the loader function to load templates from the given directory

### package(name, path) Static Method |
Loader factory for loading templates from egg package data. Parameters: `name` - the name of the package containing the resources `path` - the path inside the package data Returns: `function` the loader function to load templates from the given package

### prefixed(**delegates) Static Method |
Factory for a load function that delegates to other loaders depending on the prefix of the requested template path. The prefix is stripped from the filename when passing on the load request to the delegate.
    >>> load = prefixed(
    ...     app1 = lambda filename: ('app1', filename, None, None),
    ...     app2 = lambda filename: ('app2', filename, None, None)
    ... )
    >>> print(load('app1/foo.html'))
    ('app1', 'app1/foo.html', None, None)
    >>> print(load('app2/bar.html'))
    ('app2', 'app2/bar.html', None, None)
Parameters: `delegates` - mapping of path prefixes to loader functions Returns: `function` the loader function