OLD | NEW |
(Empty) | |
| 1 # coding: utf-8 |
| 2 |
| 3 """ |
| 4 This module supports customized (aka special or specified) template loading. |
| 5 |
| 6 """ |
| 7 |
| 8 import os.path |
| 9 |
| 10 from pystache.loader import Loader |
| 11 |
| 12 |
| 13 # TODO: add test cases for this class. |
| 14 class SpecLoader(object): |
| 15 |
| 16 """ |
| 17 Supports loading custom-specified templates (from TemplateSpec instances). |
| 18 |
| 19 """ |
| 20 |
| 21 def __init__(self, loader=None): |
| 22 if loader is None: |
| 23 loader = Loader() |
| 24 |
| 25 self.loader = loader |
| 26 |
| 27 def _find_relative(self, spec): |
| 28 """ |
| 29 Return the path to the template as a relative (dir, file_name) pair. |
| 30 |
| 31 The directory returned is relative to the directory containing the |
| 32 class definition of the given object. The method returns None for |
| 33 this directory if the directory is unknown without first searching |
| 34 the search directories. |
| 35 |
| 36 """ |
| 37 if spec.template_rel_path is not None: |
| 38 return os.path.split(spec.template_rel_path) |
| 39 # Otherwise, determine the file name separately. |
| 40 |
| 41 locator = self.loader._make_locator() |
| 42 |
| 43 # We do not use the ternary operator for Python 2.4 support. |
| 44 if spec.template_name is not None: |
| 45 template_name = spec.template_name |
| 46 else: |
| 47 template_name = locator.make_template_name(spec) |
| 48 |
| 49 file_name = locator.make_file_name(template_name, spec.template_extensio
n) |
| 50 |
| 51 return (spec.template_rel_directory, file_name) |
| 52 |
| 53 def _find(self, spec): |
| 54 """ |
| 55 Find and return the path to the template associated to the instance. |
| 56 |
| 57 """ |
| 58 if spec.template_path is not None: |
| 59 return spec.template_path |
| 60 |
| 61 dir_path, file_name = self._find_relative(spec) |
| 62 |
| 63 locator = self.loader._make_locator() |
| 64 |
| 65 if dir_path is None: |
| 66 # Then we need to search for the path. |
| 67 path = locator.find_object(spec, self.loader.search_dirs, file_name=
file_name) |
| 68 else: |
| 69 obj_dir = locator.get_object_directory(spec) |
| 70 path = os.path.join(obj_dir, dir_path, file_name) |
| 71 |
| 72 return path |
| 73 |
| 74 def load(self, spec): |
| 75 """ |
| 76 Find and return the template associated to a TemplateSpec instance. |
| 77 |
| 78 Returns the template as a unicode string. |
| 79 |
| 80 Arguments: |
| 81 |
| 82 spec: a TemplateSpec instance. |
| 83 |
| 84 """ |
| 85 if spec.template is not None: |
| 86 return self.loader.unicode(spec.template, spec.template_encoding) |
| 87 |
| 88 path = self._find(spec) |
| 89 |
| 90 return self.loader.read(path, spec.template_encoding) |
OLD | NEW |