template文件的导入
template文件就是普通的文件,需要用于template.render()函数渲染,可以有以下
几种方法来加载文件
1.用python自带的open()函数,如:
from django.template import Template, Context
from django.http import HttpResponse
import datetime
def current_datetime(request):
now = datetime.datetime.now()
# Simple way of using templates from the filesystem.
# This is BAD because it doesn't account for missing files!
fp = open('/home/djangouser/templates/mytemplate.html')
t = Template(fp.read())
fp.close()
html = t.render(Context({'current_date': now}))
return HttpResponse(html)
这种方法有点费事儿,需要打开和关闭文件
2.用template的加载api
在项目的settings.py文件中,找到TEMPLATE_DIRS,然后添加近你的template的目录
如:
TEMPLATE_DIRS = (
'/home/django/mysite/templates',
)
注意,后面有一个逗号,这个是python的元组中特别规定的
这中方法有点古板
3.将template文件创建在你的项目下,这样查找就比较 方便了,可以这样:
Django中template导入文件
最新推荐文章于 2025-02-11 14:17:21 发布
