Mat*_*pel 57 django django-templates django-urls
有没有办法在Django模板中获取当前页面URL及其所有参数?
例如,一个可以打印完整URL的模板标签 /foo/bar?param=1&baz=2
Sam*_*lan 71
编写自定义上下文处理器.例如
def get_current_path(request):
return {
'current_path': request.get_full_path()
}
Run Code Online (Sandbox Code Playgroud)
在您的TEMPLATE_CONTEXT_PROCESSORS设置变量中添加该函数的路径,并在模板中使用它,如下所示:
{{ current_path }}
Run Code Online (Sandbox Code Playgroud)
如果要request在每个请求中包含完整对象,可以使用内置django.core.context_processors.request上下文处理器,然后{{ request.get_full_path }}在模板中使用.
看到:
Mar*_*mro 23
在上下文处理器中使用Django的构建来获取模板上下文中的请求.在设置中添加request处理器TEMPLATE_CONTEXT_PROCESSORS
TEMPLATE_CONTEXT_PROCESSORS = (
# Put your context processors here
'django.core.context_processors.request',
)
Run Code Online (Sandbox Code Playgroud)
在模板中使用:
{{ request.get_full_path }}
Run Code Online (Sandbox Code Playgroud)
这样您就不需要自己编写任何新代码了.
在文件context_processors.py(或类似)中:
def myurl( request ):
return { 'myurlx': request.get_full_path() }
Run Code Online (Sandbox Code Playgroud)
在settings.py中:
TEMPLATE_CONTEXT_PROCESSORS = (
...
wherever_it_is.context_processors.myurl,
...
Run Code Online (Sandbox Code Playgroud)
在您的template.html中:
myurl={{myurlx}}
Run Code Online (Sandbox Code Playgroud)
如果我们访问以下 URL:http://127.0.0.1:8000/home/?q=test
然后
request.path = '/home/'
request.get_full_path() = '/home/?q=test'
request.build_absolute_uri() = 'http://127.0.0.1:8000/home/?q=test'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
71103 次 |
| 最近记录: |