Django:使用不同的模板反转 URL
如何反转 URL 但使用不同的模板名称?我特别必须使用 urlresolvers.reverse
更具体地说:
我有一个视图,但有两个可以访问它的网址
(r'^url/$', 'view1', {'template1':'template1.html'}, 'access-url1'),
(r'^url_dynamic/$', 'view1', {'template1':'template_dynamic.html'}, 'url-dynamic'),
我不想编写任何代码来区分视图中返回的模板因为我可能想即时更改它。因此,我需要在调用时灵活地更改 url,例如,
urlresolvers.reverse('view1', kwargs = {'template1':'template_dynamic.html'})
(which btw does not work throws noreversematch)
我也可以将 view1
复制到 view2
中,并使用 url-dynamic 调用它,但这会违反 DRY。
How can I reverse a url but with a different template name? I specifically have to use urlresolvers.reverse
To be more specific:
I have one view but two urls from which it could be accessed
(r'^url/
I don't want to write any code differentiating what template to return in the view because I might want change it on the fly. So I need the flexibility to change the url while calling it for eg
urlresolvers.reverse('view1', kwargs = {'template1':'template_dynamic.html'})
(which btw does not work throws noreversematch)
I could also just copy view1
into view2
and call it with url-dynamic but that would violate DRY.
, 'view1', {'template1':'template1.html'}, 'access-url1'),
(r'^url_dynamic/
I don't want to write any code differentiating what template to return in the view because I might want change it on the fly. So I need the flexibility to change the url while calling it for eg
I could also just copy view1
into view2
and call it with url-dynamic but that would violate DRY.
, 'view1', {'template1':'template_dynamic.html'}, 'url-dynamic'),
I don't want to write any code differentiating what template to return in the view because I might want change it on the fly. So I need the flexibility to change the url while calling it for eg
I could also just copy view1
into view2
and call it with url-dynamic but that would violate DRY.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
urlresolvers.reverse
反转与 url 中的regex
模式匹配的kwargs
,而不是通过 dict 传递的 kwargs。您可能想改用
reverse('url-name')
变体。对于你的情况,它将是:
urlresolvers.reverse
reverseskwargs
that match those in theregex
pattern, not the kwargs passed via the dict, in the url.You might want to use the
reverse('url-name')
variant instead.For your case it is going to be:
如果您确实必须使用反向来完成此操作,您可以对您的 kwargs 进行一些偷偷摸摸的操作,以将模板名称传递给它。
verse() 的函数签名如下所示:
您需要视图函数接受模板名称/字符串作为(可选)参数。那么你只需
If you really must use reverse to accomplish this, you could do something sneaky with your kwargs to pass it the template name.
The function signature for reverse() looks like this:
You would need your view function to accept a template name/string as an (optional) argument. Then you'd just