Django 模板(Templates)
前面都是用简单的 django.http.HttpResponse 来把内容显示到网页上,那么如何使用渲染模板的方法来显示内容呢。
什么是Templates
HTML文件
使用了Django模板语言(Django Tamplate Language DTL)
可以使用第三方模板
开发Template
在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
在index.html 中写一些内容
<!DOCTYPE html>
<html>
<head>
<title>欢迎光临</title>
</head>
<body>
<h1>hello blog</h1>
</body>
</html>
在view.py中返回render()
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,'index.html')
运行开发服务器(python manage.py runserver
),打开localhost:8000/blog/home(自己在urls里设的)查看效果
DTL初步使用
rander()函数的第三个参数是用来传递数据到前端的,支持dict类型参数(字典,键值对)
该字典是后台传递到模板的参数,键为参数名
在模板中使用{{参数名}}来直接使用
在view.py中返回render()
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return render(request,'index.html',{'hello':'hello,blog!!!'})
修改index.html 中写一些内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>{{ hello }}</h1>
</body>
</html>
注意点
Django按照settings.py中INSTALLED_APP中的添加顺序查找Templates
不同APP下Templates目录下的同名html文件会造成冲突
解决方法:
在APP的Templates目录下创建以APP名为名称的目录,将html文件放在该目录下
myblog
├── blog1
│ ├── __init__.py
│ ├── admin.py
│ ├── models.py
│ ├── templates
│ │ └── blog
│ │ ├── index.html
│ │ └── search.html
│ ├── tests.py
│ └── views.py
├── blog2
│ ├── __init__.py
│ ├── admin.py
│ ├── models.py
│ ├── templates
│ │ └── blog2
│ │ ├── index.html
│ │ └── poll.html
│ ├── tests.py
│ └── views.py
├── manage.py
└── myblog
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
修改view.py中render函数的路径
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return render(request,'blog/index.html',{'hello':'hello,blog!!!'})
打开localhost:8000/blog/home 和 localhost:8000/blog2/home 查看效果