Django 1.8 引入新的模板引擎配置系統,TEMPLATES 為列表,每項是一個字典,定義一個模板引擎的完整選項。
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True, # 自動掃描各應用的 templates 子目錄
},
]
| 選項 | 默認值 | 說明 |
|---|---|---|
| BACKEND | 無 | 模板引擎類路徑。內置:django.template.backends.django.DjangoTemplates、django.template.backends.jinja2.Jinja2。也可用第三方完整路徑。 |
| NAME | 引擎類名最後一段 | 引擎別名,用於渲染時指定引擎。所有引擎別名必須唯一。 |
| DIRS | [] | 模板文件搜索目錄列表,按順序查找。建議使用絕對路徑。 |
| APP_DIRS | False | 是否在 INSTALLED_APPS 的 templates 子目錄查找。通常設為 True。 |
| OPTIONS | {} | 傳遞給具體引擎的額外參數,不同引擎選項不同。 |
OPTIONS = {
'context_processors': [ # 替代舊 TEMPLATE_CONTEXT_PROCESSORS
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
'debug': True, # 替代舊 TEMPLATE_DEBUG
'loaders': [ # 替代舊 TEMPLATE_LOADERS
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
],
'string_if_invalid': '', # 替代舊 TEMPLATE_STRING_IF_INVALID
}
| 舊設置 | 新替代方式 |
|---|---|
| TEMPLATE_CONTEXT_PROCESSORS | OPTIONS['context_processors'] |
| TEMPLATE_DEBUG | OPTIONS['debug'] |
| TEMPLATE_DIRS | DIRS |
| TEMPLATE_LOADERS | OPTIONS['loaders'] |
| TEMPLATE_STRING_IF_INVALID | OPTIONS['string_if_invalid'] |
TEMPLATES = [
{
'NAME': 'django',
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [...],
},
},
{
'NAME': 'jinja2',
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'DIRS': [BASE_DIR / 'jinja2_templates'],
'APP_DIRS': True,
'OPTIONS': {
'environment': 'myproject.jinja2.environment',
},
},
]
渲染時指定引擎:render(request, 'template.html', context, using='jinja2')。
TEMPLATE_DIRS 內容移至首個引擎的 DIRS。TEMPLATE_CONTEXT_PROCESSORS 移至 OPTIONS['context_processors'],注意模塊路徑變更(django.core.context_processors → django.template.context_processors)。TEMPLATE_DEBUG 移至 OPTIONS['debug']。TEMPLATE_LOADERS 移至 OPTIONS['loaders']。新系統支持多引擎共存、更清晰的配置隔離,是邁向現代 Django 開發的關鍵一步。