Login

Automatically create urls for templates in a directory

Author:
blackrobot
Posted:
November 1, 2011
Language:
Python
Version:
Not specified
Score:
0 (after 0 ratings)

When developing a site, I sometimes want to be able to visually reference the HTML before it's given a real context, and a view. This extra bit of code will allow you to add a directory within your templates dir, and pull any html files and subdirectories from it. I added the if statement to automatically use an index.html file if there's no file and extension at the end. You can substitute anything you like for the "html" in "(?P<base>html)". That's just passed as an argument to prepend to the template as a base directory for the templates.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
from django.conf import settings
from django.conf.urls.defaults import patterns, url, include
from django.views.generic.simple import direct_to_template


urlpatterns = patterns('',
    # Example:
    # (r'^news/', include('news.foo.urls')),
)

if getattr(settings, "DEBUG", False):
    # Load template urls for reference
    def h(*args, **kwargs):
        t = "%s/%s" % (kwargs['base'], kwargs['template'])
        if t.endswith('/'):
            t = "%sindex.html" % t
        kwargs['template'] = t
        return direct_to_template(*args, **kwargs)

    urlpatterns = patterns('',
        url(r"^(?P<base>html)/(?P<template>.*)$", h),
    ) + urlpatterns

More like this

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

Comments

jumpifzero (on November 4, 2011):

Interesting! Thanks :)

#

Please login first before commenting.