问题描述
我可以访问 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 不过.
推荐答案
在视图中,可以访问 URL args
和 kwargs
作为 self.args
和 self.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
添加到上下文中,因此您可以将以下内容添加到您的模板中:
{{ view.kwargs.this_name }}
这篇关于从 Django 模板中的 URL 访问 kwargs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!