Automatic urls for static pages

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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

More like this

  1. Default to a static template. by arthurfurlan 4 years, 11 months ago
  2. @url decorator - getting rid of urlpatterns by southern_sun 6 years, 7 months ago
  3. Generic AJAX app by Rupe 4 years, 10 months ago
  4. direct to template from a subdir by Scanner 5 years, 6 months ago
  5. Smart append slash middleware by akaihola 6 years, 2 months ago

Comments

diegorusso (on November 11, 2010):

Great snippet!!! Thank you!

#

pabloberbell (on November 12, 2010):

That's awesome!

#

(Forgotten your password?)