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

Comments

jumpifzero (on November 4, 2011):

Interesting! Thanks :)

#

Please login first before commenting.