import os
from django.conf import settings
from django.views.generic.simple import direct_to_template
class StaticUrls(object):
"""
This class allow to automatically find any template file that ends
with .static.html and set up for each one an url address for
direct redirection.
Eg.
/about/ will redirect to /project/path/templates/about.static.html
/contact/email/ will redirect to /project/path/templates/contact/email.static.html
"""
def listfiles(self,dir,path):
"""This recursive method search file that ends with .static.html in a directory tree"""
files = []
for res in os.listdir(dir):
# Directory
if os.path.isdir(os.path.join(dir,res)):
# If element is a directory i do a recursive call
files += self.listfiles(
dir=os.path.join(dir,res),
path=os.path.join(path,res)
)
# Files
else:
# If element is a file, i check filename end and, if positive,
# i add path and url to a list
if res.endswith(".static.html"):
files.append({
"url": os.path.join(path,res.replace(".static.html","")),
"file":os.path.join(path,res),
})
return files
def discover(self):
"""This method will scan any template dir and add url for each valid static file"""
template_dirs = settings.TEMPLATE_DIRS
patterns = []
for td in template_dirs:
urls = self.listfiles(td,"")
for url in urls:
# i will create a list with the same struct of django url pattern.
# direct_to_template is a django view function for redirection to
# files
patterns.append((
r'^%s/$' % url['url'],
direct_to_template,
{'template':url['file']},
))
return patterns
Comments
Great snippet!!! Thank you!
#
That's awesome!
#