Reading path in templates [duplicate]
is there any way to read the path to the current pag开发者_JS百科e? For example, I am at www.example.com/foo/bar/ - and I want to read '/foo/bar/'. I have to do this in the template file without modifying views, and I have too many view files to edit each one.
Cheers.
If you add django.core.context_processors.request
to your TEMPLATE_CONTEXT_PROCESSORS
setting, it will add the request
variable to every template-rendering that uses a RequestContext
(which is most of the built-in ones). This is the HTTPRequest
object for the current request, the path
attribute of which is the requested path. More information can be found in the docs.
request.path
I ended up using this but ran into a little hiccup along the way. Here's my solution path in the hopes that I save someone else some time.
At first I added this line to my settings.py file:
TEMPLATE_CONTEXT_PROCESSORS = ("django.core.context_processors.request",)
I found that it allowed me to access the request path from within a template which had been passed a RequestContext
by using the template variable {{ request.path }}
. However, it also disabled all the other context processors. To fix this I tried adding the defaults to the TEMPLATE_CONTEXT_PROCESSORS
tuple. At first this failed because I had used the context processors for Django 1.2 (I have Django 1.1 installed). After fixing that problem I was left with the following settings file:
TEMPLATE_CONTEXT_PROCESSORS = ("django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.request",
)
精彩评论