在根目录下创建templates模板文件夹
可以再创建子文件夹放各个应用的template
在settings中 的 templates 的 DIRS中 添加模板文件目录
'DIRS' : [ os.path.join(BASE_DIR,'template') ],
BASE_DIR 就是项目目录的绝对路径
在views.py 中使用模板文件
1. 加载模板文件
去模板目录下获取html文件的内容 得到一个模板对象
2. 定义模板上下文
向模板文件传递数据
3.模板渲染
得到一个标准的html内容 把变量替换成对应的html格式
from django.template import loader
def index(request):
# 加载模板文件 模板对象
temp = loader.get_template('booktest/index.html')
# 定义模板上下文 给模板文件传递数据
context = RequestContext( request, {})
# 模板渲染 产生标准的html内容
res_html = temp.render(context)
# 返回给浏览器
return HttpResponse(res_html)
def my_render(request,template_path,context_dict={}):
temp = loader.get_template(template_path)
context = RequestContext(request,context_dict)
res_html = temp.render(context)
return HttpResponse(res_html)
def index(request):
return my_render(request,'booktest/index.html')
模板不仅仅是html文件 可以放变量
def index(request):
return my_render(request,'booktest/index.html',{'content':'hello world'})
传变量给模板文件
使用模板变量
在html文件中添加变量
{{ content }}
在模板文件中使用for循环
<ul>
{% for i in list %}
<li> {{i}} </li>
{% endfor %}
</ul>
Djangle 模板的使用
最新推荐文章于 2024-09-13 13:54:41 发布