django路由和模板

编辑器打开  mysite/mysite/urls.py
from django.conf.urls import patterns, include, url
from mysite.views import hello,index,test,home,edit #引入视图文件mysite/mysite/views.py   urlpatterns = patterns('',#正则路由
    url(r'^$',home),
    url(r'^hello/index$', index),
    url(r'^hello/hello$', hello),
    url(r'^hello/test$', test),
    url(r'^hello/edit/\d+$',edit),
) 

我们建了几个路由,指向了mysite/mysite/views.py 文件的几个方法(hello,index,test,home,edit),我们进去建这几个方法

from django.http import HttpResponse
from django.shortcuts import render_to_response

import datetime

class myclass(object):
	def __init__(self,name,age,sex):
		self.name = name
		self.age = age
		self.sex = sex

def hello(request):
	return HttpResponse('hello world')

def index(request):
	return HttpResponse('Hello world index')

def home(request):
	now = datetime.datetime.now()
	html = "<h1>%s.</h1>" % now
	return HttpResponse(html)

def edit(request):
	return HttpResponse("id is 12")

def test(request):
	mylist = ["one","two",3,4]
	mymap = {'name':'tongjh','age':22,'sex':'nan'}
	my_class = myclass('zhangsan',25,'nv')
	return render_to_response('index.html',{'title':'title','mylist':mylist,'mymap':mymap,'myclass':myclass})

我们看到test方法中使用了模板 return render_to_response('index.html',{'title':'title','mylist':mylist,'mymap':mymap,'myclass':myclass}) 这里是指使用templates下的index.html,我上篇博客安装篇中有介绍配置template的位置,第二个参数是分配变量,我分配了 list,map,class和普通变量,看看模板中是怎么解析的

打开mysite/mysite/templates/index.html文件

<html>
	<head>
		<title>{{title}}</title>
	</head>
	<body>
		<ul>
			<li>{{mylist.0}}</li>
			<li>{{mylist.1}}</li>
			<li>{{mylist.2}}</li>
			<li>{{mylist.3}}</li>
		</ul>
		<div> name : {{mymap.name}},age:{{mymap.age}},sex:{{mymap.sex}} </div>
		<div> myclass : {{my_class.name}}--{{my_class.age}}--{{my_class.sex}} </div>
		
		<div>
			{% if mymap%}
				ok {{mymap.name}}
			{% else %}
				not mymap
			{% endif %}
		</div>

		<div> 
			{% for my in mylist %}
				{{ forloop.counter }}:  {{my}}<br>
			{% endfor %}
		</div>

		<div>
			{% for k,v in mymap.items %}
				<li>{{k}} : {{v}}</li>
			{% endfor %}
		</div>

	</body>
</html>



关于django大象哥推荐大家看这个中文文档,http://djangobook.py3k.cn/2.0/




你可能感兴趣的:(django路由和模板)