需要教程的请关注个人微信公众号


模板:产生html,用于控制页面的展示,模板不仅仅是一个html文件,它包含两部分内容:

  1. 静态内容:css,js,image
  2. 动态内容:用模板语言语言动态的产生一些网页内容

模板文件的使用

  1. 在项目目录下创建模板文件夹templates
  2. 配置模板目录,在setting.py 里面有一个TEMPLATES项DIRS
'DIRS': [os.path.join(BASE_DIR,'templates')],  # 配置模板目录,默认是[],里面是空的

BASE_DIR:获取项目的绝对路径,与templates进行拼接
  1. 创建html文件:在templates下创建html文件
  2. 使用模板文件
    4.1.加载模板文件:去模板目录下获取html文件的内容,得到一个模板对象
    4.2.定义模板上下文:项模板文件传递数据
    4.3.模板渲染:得到一个标准的html内容
def index(request):
# return HttpResponse("hello django")
# 使用模板文件
# 1.加载模板文件,返回的是模板对象
temp = loader.get_template('booktest/index.html')
# 2.定义模板上下文:给模板文件传递数据
context=RequestContext(request,{})
context={}
# 3.模板渲染
res_html=temp.render(context)
# 4.返回给浏览器
return HttpResponse(res_html)

上面的方法不够灵活,如果还有页面,又要重新写一遍,自己封装一个函数

def my_render(request,template_path,context_dict):

    temp = loader.get_template(template_path)
# context=RequestContext(request,context_dict)
context=context_dict
res_html=temp.render(context)
return HttpResponse(res_html) def index(request):
return my_render(request,'booktest/index.html',{})

模板参数传递

views.py:
return my_render(request,'booktest/index.html',{'now':now,'list':list(range(1,10))}) index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h>您好,这是一个模板文件</h><br/>
now变量:<br/>{{now}}<br/>
遍历变量:<br/>
<ul>
{% for i in list%}
<li>{{i}}</li>
{% endfor %}
</ul>
</body>
</html>

变量写在{{模板变量名}}中,代码段写在{% %}中

最新文章

  1. wex5 实战 用户点评与提交设计技巧
  2. 加州大学伯克利分校Stat2.2x Probability 概率初步学习笔记: Final
  3. Android学习笔记——TableLayout
  4. 【转载-好文】使用 Spring 2.5 注释驱动的 IoC 功能
  5. ESL python调用C模块时传递unicode字符串报错问题解决
  6. linux 进入mysql
  7. iOS第三方支付-支付宝支付
  8. 2013山东省ICPC结题报告
  9. Unity3D之ScriptableObject学习笔记
  10. Nginx-location配置指南
  11. acm-DP整理
  12. 事件tou
  13. 苹果被拒的血泪史。。。(update 2015.11)
  14. BZOJ 1613: [Usaco2007 Jan]Running贝茜的晨练计划
  15. Otacle表查询
  16. Python超级明星WEB框架Flask
  17. 登录界面输入判断为空的bug
  18. require.js按需加载使用简介
  19. OOP的魔术方法
  20. Python sqlite3操作笔记

热门文章

  1. 视频发布 2019 中国.NET 开发者峰会
  2. Selnium IDE插件的安装与简单使用
  3. [Java并发] AQS抽象队列同步器源码解析--独占锁释放过程
  4. 【Git】本地分支
  5. django查询中模糊的知识点,filter(blog=blog),filter(username=username).first()--这两者只需一招让你分清QuerySet对象,和用户字典对象
  6. 在MySQL中group by 是什么意思
  7. VS2019 开发Django(七)------VS2019不能格式化html代码
  8. Swoole协程与传统fpm同步模式比较
  9. 在Join中使用FIND_IN_SET
  10. javascript中引用传递的问题如何解决