1 from django.conf import settings
2 from django.template.loaders import filesystem
3 from django.template import TemplateDoesNotExist, Template as DJTemplate
4 from django.conf import settings as djsettings
8 UNEXISTENT_TEMPLATE = object()
10 SKINS_FOLDER = os.path.dirname(__file__)
11 SKIN_TEMPLATES_FOLDER = 'templates'
12 DEFAULT_SKIN_NAME = 'default'
15 class Template(object):
17 def __init__(self, file_name):
18 self._file_name = file_name
22 return os.path.getmtime(self._file_name)
24 def _check_mtime(self):
25 if self._last_mtime is None:
28 return self._last_mtime == self._get_mtime()
32 f = open(self._file_name, 'r')
33 self._source = DJTemplate(f.read())
37 self._last_mtime = self._get_mtime()
40 self._last_mtime = None
44 def return_tuple(self):
45 if not (self._loaded and self._check_mtime()):
49 raise TemplateDoesNotExist, self._file_name
51 return self._source, self._file_name
53 class BaseTemplateLoader(object):
59 def __call__(self, name=None, dirs=None):
63 return self.load_template(name, dirs)
65 def load_template(self, name, dirs=None):
66 if not djsettings.TEMPLATE_DEBUG:
67 if name in self.cache:
68 if self.cache[name] is UNEXISTENT_TEMPLATE:
69 raise TemplateDoesNotExist, name
72 return self.cache[name].return_tuple()
76 template = self.load_template_source(name, dirs)
78 if template is not None:
79 if not djsettings.DEBUG:
80 self.cache[name] = template
82 return template.return_tuple()
84 if not djsettings.DEBUG:
85 self.cache[name] = UNEXISTENT_TEMPLATE
87 raise TemplateDoesNotExist, name
89 def load_template_source(self, name, dirs=None):
90 raise NotImplementedError
93 class SkinsTemplateLoader(BaseTemplateLoader):
95 def load_template_source(self, name, dirs=None):
96 file_name = os.path.join(SKINS_FOLDER, settings.OSQA_DEFAULT_SKIN, SKIN_TEMPLATES_FOLDER, name)
98 if os.path.exists(file_name):
99 return Template(file_name)
101 file_name = os.path.join(SKINS_FOLDER, DEFAULT_SKIN_NAME, SKIN_TEMPLATES_FOLDER, name)
103 if os.path.exists(file_name):
104 return Template(file_name)
108 load_template_source = SkinsTemplateLoader()
111 def find_media_source(url):
112 """returns url prefixed with the skin name
113 of the first skin that contains the file
114 directories are searched in this order:
115 settings.OSQA_DEFAULT_SKIN, then 'default', then 'commmon'
116 if file is not found - returns None
117 and logs an error message
119 while url[0] == '/': url = url[1:]
124 skins = n(j(d(d(__file__)),'skins'))
126 media = os.path.join(skins, settings.OSQA_DEFAULT_SKIN, url)
128 use_skin = settings.OSQA_DEFAULT_SKIN
131 media = j(skins, 'default', url)
135 media = j(skins, 'common', url)
140 logging.error('could not find media for %s' % url)
143 return use_skin + '/' + url