模板加载

  • 加载模板
  • django.template.loader 这个模块提供了两种方法加载模板
  • 加载指定模板并返回Template对象
get_template(template_name, using=None)
  • 加载指定模板并返回Template对象
select_template(template_name_list, using=None)
  • 创建模板目录
[root@ES-10-1-21-55-B28 dashboard]# mkdir templates   #前端页面都放在templates目录下面
  • 创建一个test.html文件测试
输入内容"测试html"
  • 从 文件中加载内容
from django.template import Context, loader
def index(request):
  t = loader.get_template("test.html")
  context = {"name": "study python !!!"}         #字典可以在html文件用{{ name }}获取值,name相当于一个变量,固定写法  通过{{}}把值传给模板
  return HttpResponse(t.render(context, request))
  • 快捷方式和上面方法效果一样
from django.shortcuts import render
  def index(request):
    context = {'name': "study python"}   
    return render(request, 'test.html', context)  #request必传的参数,当前请求都存在request参数里面
  •  前端访问html页面内容就可以通过前端展示了
原文地址:https://www.cnblogs.com/jiaqili/p/14264462.html