2012-02-15 82 views
0

我想创建一个TemplateView来显示特定目录下的所有模板。创建一个视图到Django中的模板子目录

所以,比如我有

/staticpages/about-me.html 
/staticpages/about-you.html 
/staticpages/about-us.html 

...

(更多)

在我的urls.py我有 ..

url(r'^(?P<page_name>[-\w]+)/$', StaticPageView.as_view()), 

..

在我的views.py我有

class StaticPageView(TemplateView): 
    def get_template_names(self): 
     return 'staticpages/%s' % self.kwargs['page_name'] 

但是,如果有人去的URL /staticpages/blahblah.html(不存在),它获取此视图所接受并生成一个模板未找到错误。如果找不到模板,我可以重定向到404吗?

或者还有更好的方法来做到这一点?

回答

0

你可以考虑使用将会给你模板目录的项目设置。然后可以使用os.listdir(http://docs.python.org/library/os.html#os.listdir)列出该目录中存在的所有模板。这是如何实现它的。 (下面的代码没有进行测试..它只是给你一个想法)

的模板列表可以显示这样的:

# views.py 
import os 
from django.conf import settings 

template_directory = os.path.join(settings.TEMPLATE_DIRS,'sub_directory') 
templates = os.listdir(template_directory) 
return render_to_response('template_list.html') 

相应的模板文件..

# template_list.html 
<ul> 
{% for template in templates %} 
    <li> <a href="/{{template}}"> {{template.filename}} </a> </li> 
{% endfor %} 
</ul> 

希望有帮助..