Django的Templates

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/84668336

一 什么是Templates

1 HTML文件

2 使用Django模板语言(Django Tempatle Languange,DTL)

3 可以使用第三方模板(如jinja2)

二 开发第一个Template

1 步骤

1.1 在APP的根目录下创建名叫templates的目录

1.2 在templates下创建HTML文件

1.3 在views.py中返回render()

2 实战——简单模板

2.1 模板文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Hello,Blog!</h1>
</body>
</html>

2.2 views.py

from django.shortcuts import render
from django.http import HttpResponse

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

2.3 测试结果

三 DTL初步使用

  • render()函数中支持一个dict类型参数

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

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

四 实战——使用参数

1 模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>{{hello}}</h1>
</body>
</html>

2 views.py

from django.shortcuts import render
from django.http import HttpResponse

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

3 测试结果

五 注意

1 Django查找Template

Django按照INSTALLED_APPS中的添加顺序查找Templates

不同APP下Templates目录中的同名.html文件会造成冲突

六 针对同名文件冲突解决

在APP的Templates目录下创建以APP名为名称的目录

将html文件放入新创建的目录下

修改相应urls.py文件中的路径

1 项目结构

2 应用blog相关文件

2.1 inde.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Hello,Blog1</h1>
</body>
</html>

2.2 urls.py

from django.conf.urls import url,include
from . import views
urlpatterns = [
    url(r'^index/$', views.index),
]

2.3 views.py

from django.shortcuts import render
from django.http import HttpResponse

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

3 应用blog2相关文件

3.1 index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Hello,blog2</h1>
</body>
</html>

3.2 urls.py

from django.conf.urls import url,include
from . import views
urlpatterns = [
    url(r'^index/$', views.index),
]

3.3 views.py

from django.shortcuts import render
from django.http import HttpResponse

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

4 运行结果

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/84668336
今日推荐