从 Django 模板中的 URL 访问 kwargs [英] Access kwargs from a URL in a Django template

查看:31
本文介绍了从 Django 模板中的 URL 访问 kwargs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以访问 Django 模板中命名参数的值(来自 URL)吗?

Can I access value of a named argument (from the URL) in a Django template?

比如我可以从 django 模板访问下面 this_name 的值吗?

Like can I access the value of this_name below from a django template?

url(r'^area/(?P<this_name>[w-]+)/$', views.AreaView.as_view(), name="area_list")

我可以获取整个 URL 路径并将其分解,但想检查是否有直接的方法可以做到这一点,因为它已经有了一个名称.

I could get the whole URL path and break it up but wanted to check if there's a straight forward way to do that, since it already has a name.

在视图的上下文数据中传递它可能是另一种选择,但不确定我是否确实需要传递它,因为我猜模板已经以某种方式拥有它?在 请求 API<中找不到直接方法/a> 不过.

Passing it down in the context data from the view may be an alternative but not sure if I do need to pass it down since I'd guess the template would already have it somehow? Couldn't find a direct method in the request API though.

推荐答案

在视图中,可以访问 URL argskwargs 作为 self.argsself.kwargs.

In the view, you can access the URL args and kwargs as self.args and self.kwargs.

class MyView(View):
    def my_method(self):
        this_name = self.kwargs['this_name']

如果您只想访问模板中的值,则无需在视图中进行任何更改.基础 get_context_data/a> 方法将视图作为 view 添加到上下文中,因此您可以将以下内容添加到您的模板中:

If you only want to access the value in the template, then you don't need to make any changes in the view. The base get_context_data method adds the view to the context as view, so you can add the following to your template:

{{ view.kwargs.this_name }}

这篇关于从 Django 模板中的 URL 访问 kwargs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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