Django学习案例一(blog):三.模板Templates

python学习网 2017-11-05 23:22:02

 

1.优化url配置

(1)上一节url配置用的是其中一种方式“Function views”,本节进行优化,用“Including another URLconf”方式。

Myblog/urls.py内容

from django.conf.urls import url,include  #此处添加include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^blog/', include('blog.urls')),
]

(2)blog中增加urls.py文件,内容如下:

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

2.制作模板

(1)APP(blog)中添加templates文件夹

(2)blog/templates中新增新增blog文件夹(与app名相同的文件夹)

(3)blog/templates/blog中新增html文件,取名index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>你好,世界!</h1>>
</body>
</html>

(3)blog/views.y中修改,使用渲染render

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

def index(request):
    #return HttpResponse('Hello,world!')
    return render(request,'blog/index.html')  #三个参数,1.请求对象本身,2.模板文件 3,后台传到前端的数据

显示如下:

 

 

3.DTL使用

Render()函数中支持一个dict类型参数,即以上render中提到的第3个参数;该字典是后台传递到模板的参数,键为参数名;在模板中使用 {{参数名}} 来直接使用。

修改blog.views.py和blog.templates.index.html的内容:

blog.views.py修改如下:

from django.shortcuts import render
def index(request):
    #return HttpResponse('Hello,world!')
    return render(request,'index.html',{'hello':'你好,世界!'}) 

blog.templates.index.html修改如下:

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

 

 

 

 

 

 

 

 

 

阅读(785) 评论(0)