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']更多推荐
发布评论