四. django template模版

往前端浏览器pull一些字符串,这些字符串是一些数据, 那如果想让这些数据按我们的某种格式美化一点/增加样式/图片,就需要用到django提供的模版--模版就是为了让数据看起更美观。

加载模版 django.template.loader 这个模块提供了两种方法加载模板 :
get_template(template_name, using=None) 加载指定模板并返回Template对象 :
select_template(template_name_list, using
=None) 它与get_template类似,它尝试每个名称并返回第一个存在的模板 从文件加载内容:注意此test.html模版是在当前app下的templates目录下找它 from django.template import Context, loader def index(request): t = loader.get_template("test.html") context = {"name": "hello reboot !!!"} return HttpResponse(t.render(context, request))

快捷方式:render()--会读取html文件中内容并把其中变量{{ aa }}按k/v形式做替换(做匹配看views.py中有无aa这个key,有的话就把这个aa的值去替换{{ aa }},这就是render逻辑
from django.shortcuts import render
def index(request):
  context = {'name': "reboot"}
  return render(request, 'test.html', context)
原文地址:https://www.cnblogs.com/dbslinux/p/13037567.html