Django:在模板中获取当前页面的URL,包括参数 [英] Django: get URL of current page, including parameters, in a template
问题描述
有没有办法在Django模板中获取当前页面URL及其所有参数?
Is there a way to get the current page URL and all its parameters in a Django template?
例如,一个模板标签可以打印一个完整的URL,如 / foo / bar?param = 1& baz = 2
For example, a templatetag that would print a full URL like /foo/bar?param=1&baz=2
推荐答案
编写一个自定义上下文处理器。例如
Write a custom context processor. e.g.
def get_current_path(request):
return {
'current_path': request.get_full_path()
}
在 TEMPLATE_CONTEXT_PROCESSORS
设置变量,并在您的模板中使用它:
add a path to that function in your TEMPLATE_CONTEXT_PROCESSORS
settings variable, and use it in your template like so:
{{ current_path }}
如果你想要在每一个都有请求
请求,您可以使用内置的 django.core.context_processors.request
上下文处理器,然后在模板中使用 {{request.get_full_path}}
。
If you want to have the full request
object in every request, you can use the built-in django.core.context_processors.request
context processor, and then use {{ request.get_full_path }}
in your template.
请参阅:
- 自定义上下文处理器
- < a href =http://docs.djan goproject.com/en/dev/ref/request-response/#django.http.HttpRequest.get_full_pathrel =noreferrer> HTTPRequest的get_full_path()方法。
- Custom Context Processors
- HTTPRequest's get_full_path() method.
这篇关于Django:在模板中获取当前页面的URL,包括参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!