Login

direct to template from a subdir

Author:
Scanner
Posted:
October 9, 2008
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

I needed a way to quickly get a direction of html pages templated such that another person could drop new templates in to a subdirectory and without modifying urls.py or views.py get them up and being displayed.

Now, the direct_to_template view provided django.views.generic.simple can sort of do this with a urlpattern like:

url(r'^(?P<template>.*\.html)$', direct_to_template)

But that means your templates, no matter what level in the url hierarchy they are reached at, have to be defined at the root of a template directory. I wanted them retrieved from a specific subdirectory instead so I could provide a little wall for them. Hence this snippet.

To use you would have url pattern that looked like:

url(r'^foo/(?P<template>.*\.html)$', direct_to_template, {'subdir' : 'subdir/'}),

Which will template any url that matches <parent url>/foo/bar.html for any 'bar'. The problem is if this is a sub-url pattern match this is going to look for the template "bar.html" when we may actually want it to get the template "<parent url>/foo/bar.html"

 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
def direct_to_template_subdir(request, template, subdir = None, **kwargs):
    """
    A wrapper around django's direct_to_template view. It prepend a
    given file path on to the template we are given. This lets us
    render templates in a sub-dir of the url pattern that matches this
    template.

    What do I mean?

    Take for example:

        url(r'^foo/(?P<template>.*\.html)$', direct_to_template,
            {'subdir' : 'subdir/'}),


    Which will template any url that matches <parent url>/foo/bar.html for any
    'bar'. The problem is if this is a sub-url pattern match this is going to
    look for the template "bar.html" when we may actually want it to get the
    template "<parent url>/foo/bar.html"

    Arguments:
    - `request`: django httprequest object... 
    - `template`: The template to render.
    - `subdir`: The subdir to prepend to the template.
    - `**kwargs`: kwargs to pass in to 
    """
    
    if subdir is not None:
        template = os.path.join(subdir,template)
    return direct_to_template(request, template, **kwargs)

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

Please login first before commenting.