0

在渲染模板时,我想通过提供命名空间值而不是路径来检索模板的 url。例如,而不是这个:

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

我希望能够做到以下几点:

from django.shortcuts import render
from django.core.urlresolvers import reverse

return render(request, reverse('base:index'), {'user':name})

但上面会产生错误。我该怎么做?有没有办法将命名空间赋予函数并获取实际路径?

扩展示例:

- urls.py

from django.conf.urls.defaults import patterns, include, url

urlpatterns = patterns('',
    url(r'^', include('base.urls', namespace='base')),
)

- 应用程序库:urls.py

from django.conf.urls.defaults import patterns, url

urlpatterns = patterns('base.views',
   url(r'^/?$', 'index', name='index'),
)

- 应用程序库: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'})

提前致谢。

4

1 回答 1

0

模板名称在视图中是硬编码的。您还可以做的是,您可以从 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']
于 2013-03-27T14:51:46.877 回答