Python Django模板变量
一、传递字符串变量
# cat blog/template/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>hello {{user}}</h1>
</body>
</html>
# cat blog/views.py
from django.shortcuts import render_to_response
def index(req):
return render_to_response(‘index.html‘,{‘title‘:‘Loyu page‘,‘user‘:‘loyu‘})
二、传递字典、列表变量
# cat blog/template/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>hello: {{user.name}}</h1>
<p>hello: {{user.age}}</p>
<p>hello: {{user.sex}}</p>
<p>{{book_list.0}}</p>
<p>{{book_list.1}}</p>
<p>{{book_list.2}}</p>
<p>{{book_list.3}}</p>
</body>
</html>
# cat blog/views.py
from django.shortcuts import render_to_response
def index(req):
user = {‘name‘:‘loyu‘,‘age‘:23,‘sex‘:‘male‘}
book_list = [‘python‘,‘java‘,‘php‘,‘web‘]
return render_to_response(‘index.html‘,{‘title‘:‘Loyu page‘,‘user‘:user,‘book_list‘:book_list})
三、传递类变量
# cat blog/template/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>hello: {{user.name}}</h1>
<h1>hello: {{user.age}}</h1>
<h1>hello: {{user.sex}}</h1>
</body>
</html>
# cat blog/views.py
from django.shortcuts import render_to_response
class Person(object):
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
def index(req):
user = Person(‘Loyu‘, 33, ‘male‘)
return render_to_response(‘index.html‘,{‘title‘:‘Loyu page‘,‘user‘:user})
本文出自 “流星宇” 博客,请务必保留此出处http://8789878.blog.51cto.com/8779878/1850742
原文地址:http://8789878.blog.51cto.com/8779878/1850742