Django学习:模板Templates(4)

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 查看效果

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值