您的位置:首页 > 其它

使用模板的两种方式

2014-12-22 17:48 190 查看
[root@iZ28cumdzmgZ muahao02]# vim blog/templates/index.html

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<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> muahao02</title>
</head>
<body>
<h1>hello muahao02</h1>
</body>
</html>


[root@iZ28cumdzmgZ muahao02]# vim blog/views.py

from django.template import loader,Context,Template
from django.http import HttpResponse

方式1:
def index(req):
t = loader.get_template('index.html')  #通过loader对象将index.html模板加载成t变量
c = Context({'uname':'Alen'})    #通过Context对象将内容,赋值给变量c
html = t.render(c)    #通过render方法,将内容渲染给模板
return HttpResponse(html)   #通过HttpResponse对象进行返回

方式2:
注意:在使用第2种方式的时候,需要from django.template import Template
def index1(req):
t = Template('<h1>hello {{uname}}</h1>')
c = Context({'uname':'Jack'})
return HttpResponse(t.render(c))


[root@iZ28cumdzmgZ muahao02]# vim muahao02/urls.py

from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
# Examples:
# url(r'^$', 'muahao02.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),

url(r'^index/$','blog.views.index'),
url(r'^index1/$','blog.views.index1')


本文出自 “muahao” 博客,请务必保留此出处http://muahao.blog.51cto.com/8176010/1592754
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐