Django:如何通过给出命名空间来获取模板的url?(Django: How can i get the url of a template by giving the namespace?)

编程入门 行业动态 更新时间:2024-10-28 00:21:46
Django:如何通过给出命名空间来获取模板的url?(Django: How can i get the url of a template by giving the namespace?)

当我渲染模板时,我想通过给出命名空间值而不是路径来检索模板的URL。 例如,而不是这样:

return render(request, 'base/index.html', {'user':name})

- urls.py

from django.conf.urls.defaults import patterns, include, url urlpatterns = patterns('', url(r'^', include('base.urls', namespace='base')), )

- app base:urls.py

from django.conf.urls.defaults import patterns, url urlpatterns = patterns('base.views', url(r'^/?$', 'index', name='index'), )

- app base:views.py

from django.shortcuts import render from django.core.urlresolvers import reverse def homepage(request): ''' Here instead of 'base_templates/index.html' i would like to pass something that can give me the same path but by giving the namespace ''' return render(request, 'base_templates/index.html', {'username':'a_name'})

- urls.py

from django.conf.urls.defaults import patterns, include, url urlpatterns = patterns('', url(r'^', include('base.urls', namespace='base')), )

- app base: urls.py

from django.conf.urls.defaults import patterns, url urlpatterns = patterns('base.views', url(r'^/?$', 'index', name='index'), )

- app base: views.py

from django.shortcuts import render from django.core.urlresolvers import reverse def homepage(request): ''' Here instead of 'base_templates/index.html' i would like to pass something that can give me the same path but by giving the namespace ''' return render(request, 'base_templates/index.html', {'username':'a_name'})

Thanks in advance.

最满意答案

模板名称在视图中是硬编码的。 你还可以做的是你可以从url模式传递模板名称,有关详细信息,请参阅此处 :

from django.conf.urls.defaults import patterns, url urlpatterns = patterns('base.views', url(r'^/?$', 'index', {'template_name': 'base_templates/index.html'}, name='index'), )

然后在视图中获取模板名称:

def index(request, **kwargs): template_name = kwargs['template_name']

Template names are hard coded within the view. What you can also do is that you can pass the template name from the url pattern, for more details see here:

from django.conf.urls.defaults import patterns, url urlpatterns = patterns('base.views', url(r'^/?$', 'index', {'template_name': 'base_templates/index.html'}, name='index'), )

Then in view get the template name:

def index(request, **kwargs): template_name = kwargs['template_name']

更多推荐

本文发布于:2023-08-08 01:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466715.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模板   空间   Django   url   namespace

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!