Django学习之路(五)template的学习

来源:互联网 发布:手机淘宝查排名 编辑:程序博客网 时间:2024/06/05 14:16

Template

template是简单来说就是存放HTML文件的目录

Template创建过程

一,设置template文件的路径
在项目的setting.py中找到TEMPLATES,其中会有一个属性叫DIRS,添加你要创建的文件(templates)的目录.
eg:’DIRS’:[‘blog/templates’]

二,在相应目录下新建templates
在项目的相对路径blog中新建文件templates并在其中添加html文件。
eg:在新建的templates中新建index.html

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

三,在views.py中返回render()
render是渲染的意思。
在系统的默认的views.py模板中会有
from django.shortcuts import render
我们需要将views.py改为

# -*- coding: utf-8 -*-from __future__ import unicode_literalsfrom django.shortcuts import renderfrom django.http import HttpResponsedef index(request):    return render(request,'index.html')

render()通常传递个参数,第一个是request,第二个是前端模板,*第三个是一个dict类型的参数。该字典是后台传递数据到模板的参数,键为参数名
在模板中使用{{参数名}}来直接使用。*不过我们目前没有使用第三个参数。
在这时打开浏览器的相应地址,就会出现:
这里写图片描述

四,关于render()第三个参数
第三个是一个dict类型的参数。该字典是后台传递数据到模板的参数,键为参数名
在模板中使用{{参数名}}来直接使用。
我们可以修改index.html模板为:

<h1>{{hb}}</h1>>

然后将views.py中的render函数修改:

render(request,'index.html',{'hb':'Hello,Blog'})

这时候页面也会正常响应出想要的内容

原创粉丝点击