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'
13 FORCE_DEFAULT_PREFIX = "%s/" % DEFAULT_SKIN_NAME
16 class Template(object):
18 def __init__(self, file_name):
19 self._file_name = file_name
23 return os.path.getmtime(self._file_name)
25 def _check_mtime(self):
26 if self._last_mtime is None:
29 return self._last_mtime == self._get_mtime()
33 f = open(self._file_name, 'r')
34 self._source = f.read()
38 self._last_mtime = self._get_mtime()
41 self._last_mtime = None
45 def return_tuple(self):
46 if not (self._loaded and self._check_mtime()):
50 raise TemplateDoesNotExist, self._file_name
52 return self._source, self._file_name
54 class BaseTemplateLoader(object):
60 def __call__(self, name=None, dirs=None):
64 return self.load_template(name, dirs)
66 def load_template(self, name, dirs=None):
67 if not djsettings.TEMPLATE_DEBUG:
68 if name in self.cache:
69 if self.cache[name] is UNEXISTENT_TEMPLATE:
70 raise TemplateDoesNotExist, name
73 return self.cache[name].return_tuple()
77 template = self.load_template_source(name, dirs)
79 if template is not None:
80 if not djsettings.DEBUG:
81 self.cache[name] = template
83 return template.return_tuple()
85 if not djsettings.DEBUG:
86 self.cache[name] = UNEXISTENT_TEMPLATE
88 raise TemplateDoesNotExist, name
90 def load_template_source(self, name, dirs=None):
91 raise NotImplementedError
94 class SkinsTemplateLoader(BaseTemplateLoader):
96 def load_template_source(self, name, dirs=None):
98 if name.startswith(FORCE_DEFAULT_PREFIX):
100 file_name = os.path.join(SKINS_FOLDER, DEFAULT_SKIN_NAME, SKIN_TEMPLATES_FOLDER, name[len(FORCE_DEFAULT_PREFIX):])
102 if os.path.exists(file_name):
103 return Template(file_name)
107 for skin in (settings.OSQA_DEFAULT_SKIN, DEFAULT_SKIN_NAME):
108 file_name = os.path.join(SKINS_FOLDER, skin, SKIN_TEMPLATES_FOLDER, name)
110 if os.path.exists(file_name):
111 return Template(file_name)
115 load_template_source = SkinsTemplateLoader()
118 def find_media_source(url):
119 """returns url prefixed with the skin name
120 of the first skin that contains the file
121 directories are searched in this order:
122 settings.OSQA_DEFAULT_SKIN, then 'default', then 'commmon'
123 if file is not found - returns None
124 and logs an error message
126 while url[0] == '/': url = url[1:]
131 skins = n(j(d(d(__file__)),'skins'))
133 media = os.path.join(skins, settings.OSQA_DEFAULT_SKIN, url)
135 use_skin = settings.OSQA_DEFAULT_SKIN
138 media = j(skins, 'default', url)
142 media = j(skins, 'common', url)
147 logging.error('could not find media for %s' % url)
150 return use_skin + '/' + url