您的位置:首页 > 编程语言 > Go语言

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

2017-08-14 17:40 447 查看

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_literals

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

def 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'})


这时候页面也会正常响应出想要的内容
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: