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