模板的作用方法有如下三种:
blog/views.py:
from django.template import loader, Context, Template from django.http import HttpResponse from django.shortcuts import render_to_response as r2r def index(req): t = loader.get_template('index.html') c = Context({'uname':'eli'}) html = t.render(c) return HttpResponse(html) def index1(req): t = Template('<h1>hey {{uname}} welcome to Django !</h1>') c = Context({'uname':'eli'}) return HttpResponse(t.render(c)) def index2(req): return r2r('index.html', {'uname':'man'})
对应的 urls.py:
X from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'csvt02.views.home', name='home'), # url(r'^csvt02/', include('csvt02.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), url(r'^index/$', 'blog.views.index'), url(r'^index1/$', 'blog.views.index1'), url(r'^$', 'blog.views.index2'), )
另,可以利用 manage.py 中的 shell 调试应用:
[root@bogon csvt02]# python manage.py shell Python 2.7.5 (default, Sep 20 2013, 07:02:05) [GCC 4.1.2 20080704 (Red Hat 4.1.2-52)] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.shortcuts import render_to_response as r2r >>> r2r('index.html',{'uname':'eli'}) <django.http.response.HttpResponse object at 0xa05ce6c> >>> from django.template import loader >>> t = loader.get_template('index.html') >>> t <django.template.base.Template object at 0xa0628ec> >>> from django.template import Context >>> c = Context({'uname':'eli'}) >>> c [{'False': False, 'None': None, 'True': True}, {'uname': 'eli'}] >>> t.render(c) u'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\r\n<html xmlns="http://www.w3.org/1999/xhtml">\r\n<head>\r\n\t<title>Csvt02</title>\r\n\t</head>\r\n\t<body>\r\n\t\t<h1>Hi eli welcome to Django !</h1>\r\n\t</body>\r\n</html>\r\n' >>>