学会使用渲染模板的方法来显示html内容。

一、Templates是什么:

HTML文件

使用了Django模板语言(Django Tamplate Language DTL)

可以使用第三方模板

二、开发Template

1.在app根目录下新建一个 templates 文件夹,里面新建一个index.html

myblog
├── blog
│   ├── __init__.py
│   ├── admin.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── templates
│   │   └── index.html
│   ├── tests.py
│   └── views.py
├── manage.py
└── myblog
    ├── __init__.py
    ├── settings.py
    ├── urls.py
    └── wsgi.py  

2.在index.html 中写一些内容

<!DOCTYPE html>
<html>
<head>
    <title>第一个Template</title>
</head>
<body>
<h1>Hello world</h1>
<h2>My Blog</h2>
</body>
</html> 

3.在views.py中返回render()

from django.shortcuts import render

# Create your views here.

def index(request):
    return render(request,'index.html')

4.运行cmd启动查看效果

三、初步使用DTL

rander()函数的第三个参数是用来传递数据到前端的,支持dict类型参数(字典,键值对)

该字典是后台传递到模板的参数,键为参数名

在模板中使用{{参数名}}来直接使用

1.在views.py中返回render()

from django.shortcuts import render

# Create your views here.

def index(request):
    return render(request,'index.html',{'hello':'hello,my blog!'})

2.修改index.html 中的一些内容

<!DOCTYPE html>
<html>
<head>
    <title>第一个Template</title>
</head>
<body>
<h1>Hello world</h1>
<h2>{{hello}}</h2>
</body>
</html> 

四、注意

Django按照settings.py中INSTALLED_APP中的添加顺序查找templates

不同app下templates目录下的同名html文件会造成冲突

解决方法:

在app的templates目录下创建以APP名为名称的目录,将html文件放在该目录下

然后修改view.py中render函数的路径

from django.shortcuts import render

# Create your views here.

def index(request):
    return render(request,'blog/index.html',{'hello':'hello,my blog!'})

打开http://127.0.0.1:8000/index/ 查看效果

 

最新文章

  1. hbase集群安装与部署
  2. Development of large-scale site performance optimization method from LiveJournal background
  3. Python 操作 mongodb 数据库
  4. MVC 学习(二)之Linq to Sql 简单Demo
  5. spring注解:@PostConstruct和@PreDestroy
  6. ASP.NET操作DataTable
  7. linux du 显示目录下的各个子目录的大小
  8. 几种常用的Java数据源解决方案
  9. TCP/IP他人笔记学习--地址收录
  10. 使用 Eclipse Memory Analyzer 进行堆转储文件分析
  11. ubuntu 禁用快捷键
  12. Oracle 表空间扩充
  13. freemarker常用值格式化方法
  14. Linux 工作目录切换命令
  15. 将double或则float类型保留小数
  16. Vue爬坑之路
  17. 介绍三款串口监控工具:Device Monitoring Studio,portmon,Comspy
  18. BZOJ2819Nim——树链剖分+线段树+Nim游戏
  19. 20165308 预备作业3 Linux安装及学习
  20. JSFL 获取当前脚本路径,执行其他脚本

热门文章

  1. Lua学习(5)——迭代器与泛型for
  2. Promise (1) 初步接触
  3. 如何通过JS实现简单抖动效果
  4. MD5加密算法(信息摘要算法)、Base64算法
  5. 小K的H5之旅-实战篇(一)
  6. centos 下 安装mysql
  7. MySQL存储汉字
  8. JAVA设计模式初探之装饰者模式
  9. Elasticsearch 与 Kafka 整合剖析
  10. lucene全文搜索之一:lucene的主要功能和基本结构(基于lucene5.5.3)