from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
import datetime
def current_datetime(request):
now = datetime.datetime.now()
t = get_template('current_datetime.html')
html = t.render(Context({'current_date': now}))
return HttpResponse(html)
• 如果 APP_DIRS 的值是 True ,而且使用 DTL,在当前应用中查找“templates”目录。
• 如果在当前应用中没找到模板, get_template() 把传给它的模板名称添加到 DIRS 中的各个目录后面,按顺序在各个目录中查找。假如 DIRS 的第一个元素是 '/home/django/mysite/templates' ,上述get_template() 调用查找的模板是 /home/django/mysite/templates/current_datetime.html 。
• 如果 get_template() 找不到指定名称对应的模板,抛出 TemplateDoesNotExist 异常。
本文详细解析了Django框架中模板加载的过程,包括如何在应用中查找模板,以及当在当前应用未找到模板时,Django如何在配置的目录中进行搜索。同时,介绍了get_template()函数的工作原理及其异常处理。

314

被折叠的 条评论
为什么被折叠?



