在Django项目中放置模板的最佳位置是什么?
在Django项目中,放置模板的最佳位置是什么?
10 个回答
10
DJANGO 1.11
在你的项目文件夹里,也就是有manage.py的地方,添加一个templates文件夹。这是你的基础目录。
然后在settings.py文件中,把TEMPLATES的DIRS部分改成下面这样:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
现在你可以通过下面的代码来使用这个模板:
def home(request):
return render(request,"index.html",{})
在views.py文件中。这在django 1.11中完全可以正常工作。
101
把特定于某个应用的模板放在 <PROJECT>/<APP>/templates/<APP>/template.html
这个位置,这样可以让这个应用在其他地方也能重复使用。
而对于一些通用的“全局”模板,我会把它们放在 <PROJECT>/templates/template.html
这个位置。
52
来自Django书籍的第4章,内容如下:
如果你找不到一个明显的地方来放置你的模板,我们建议你在你的Django项目中创建一个templates目录(也就是在你第二章创建的mysite目录里,如果你一直在跟着我们的例子)。
我就是这样做的,这对我来说效果很好。
我的文件夹结构大致是这样的:
/media
用来放我的CSS、JS、图片等
/templates
用来放我的模板
/projectname
用来放主要的项目代码(也就是Python代码)