如何在模板中获取当前页面的 URL,包括参数? [英] How to get URL of current page, including parameters, in a template?

查看:30
本文介绍了如何在模板中获取当前页面的 URL,包括参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 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 }}

如果你想在每个请求中都有完整的 request 对象,你可以使用内置的 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.

见:

这篇关于如何在模板中获取当前页面的 URL,包括参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆