Login

Automatic urls for static pages

Author:
jibbolo
Posted:
November 11, 2010
Language:
Python
Version:
1.2
Score:
4 (after 4 ratings)

Create in your template dir html files named example.static.html and with this snippet you can get the static page with the url /example/. If you put static file in a sub-directory, the url will be /sub-directory/example/

Example:

static_urls = StaticUrls()

urlpatterns = patterns('', *static_urls.discover())

urlpatterns += patterns('',

`(r'^admin/doc/', include('django.contrib.admindocs.urls')),`

`(r'^admin/', include(admin.site.urls)),`

)

 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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

diegorusso (on November 11, 2010):

Great snippet!!! Thank you!

#

pabloberbell (on November 12, 2010):

That's awesome!

#

Please login first before commenting.