Login

Automatically create urls for templates in a directory

Author:
blackrobot
Posted:
November 1, 2011
Language:
Python
Version:
Not specified
Tags:
urls templates direct_to_template
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. Automatic urls for static pages by jibbolo 4 years, 4 months ago
  2. direct to template from a subdir by Scanner 6 years, 5 months ago
  3. DaGood breadcrumbs by drozzy 6 years, 2 months ago
  4. Integrating Django with ToofPy by Siddhi 7 years, 8 months ago
  5. Generic AJAX app by Rupe 5 years, 9 months ago

Comments

jumpifzero (on November 4, 2011):

Interesting! Thanks :)

#

Please login first before commenting.