Python Django模板使用流程
一、创建工程项目
# django-admin.py startproject csvt02
# cd csvt02
二、创建应用
# django-admin.py startapp blog
三、添加访问url
# egrep -v "#|^$" urls.py
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns(‘‘,
url(r‘^index/$‘,‘blog.views.index‘),
url(r‘^index1/$‘,‘blog.views.index1‘),
url(r‘^index2/$‘,‘blog.views.index2‘),
)
四、添加视图文件
# cat blog/views.py
from django.template import loader,Context,Template
from django.http import HttpResponse
from django.shortcuts import render_to_response
def index(req):
t = loader.get_template(‘index.html‘) # 导入模板对象
c = Context({‘uname‘:‘loyu‘}) # 创建Context对象添加对模版渲染的数据
html = t.render(c) # 对模板进行渲染
return HttpResponse(html)
def index1(req):
t = Template(‘<h1>hello {{uname}}</ha>‘)
c = Context({‘uname‘:‘loyu‘})
html = t.render(c)
return HttpResponse(html)
def index2(req):
return render_to_response(‘index.html‘,{‘uname‘:‘loyu‘})
五、添加模板文件
# cat blog/templates/index.html
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title>{{title}}</title>
</head>
<body>
<h1>{{uname}} hello</h1>
</body>
</html>
六、启动项目工程
# python manage.py runserver