def index(request):
return HttpResponse('<h1>Hello World!</h1>')
这种直接返回html标签的方法肯定不适用,所以我们需要返回一个html页面。
在blog文件夹里创建一个新的文件templates
zhangdeMacBook-Pro:learn zhang$ mkdir blog/templates
在该文件夹里新建一个html文件,命名为index.html(例子)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hello</title>
</head>
<body>
<h1>
hello world!
</h1>
</body>
</html>
对blog/views.py进行修改
#from django.http import HttpResponse
from django.shortcuts import render_to_response #new
def index(request):
#return HttpResponse('<h1>Hello World!</h1>')
return render_to_response('index.html',{})
打开127.0.0.1:8000/blog/index即可看到标题为hello,显示内容为hello world!的网页
绑定变量(动态)
修改blog/templates/index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{title}}</title>
</head>
<body>
<h1>
hello {{name}}!
</h1>
</body>
</html>
修改blog/views.py文件
def index(request):
#return HttpResponse('<h1>Hello World!</h1>')
return render_to_response('index.html',{'title':Hello,'name':'Tom'})
再次打开上面地址,即可看到变化,尝试修改index方法的return字典,发现页面内容有变化
{{value}}中,value为列表或者字典的使用
修改blog/templates/index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{title.name}}</title>
</head>
<body>
<h1>
hello {{user.name}}!
</h1>
<li>
age:{{user.age}}
</li>
<h1>
{{list.0}},{{list.1}},{{list.2}},{{list.3}}
</h1>
</body>
</html>
修改blog/views.py文件
def index(request):
#return HttpResponse('<h1>Hello World!</h1>')
list=['a','b',23,'hello']
user={'name':'Tom','age':11}
return render_to_response('index.html',{'title':Hello,'user':user,'list':list})
创建类来进行传参
blog/views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render_to_response
# Create your views here.
class Person(object):
def __init__(self,name,age,sex):
self.name=name
self.age=age
self.sex=sex
def say(self):
return "I'm Ok. Thank you."
def index(request):
#user={'name':'Tom','age':34,'sex':'male'}
user=Person('tom',23,'male')
book_list = ['Python','java','php','web']
return render_to_response('test1.html',{'title':'Hello','user':user,'book_list':book_list})
blog/templates/index.py
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{title}}</title>
</head>
<body>
<h1>hello {{user.name}}!</h1>
<li>age:{{user.age}}</li>
<div>the {{user.name}} say {{user.say}}</div>
<li>sex:{{user.sex}}</li>
<li>{{book_list.0}}</li>
<li>{{book_list.1}}</li>
</body>
</html>