Python Django模板變量php
1、傳遞字符串變量html
# cat blog/template/index.htmljava
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">python
<head>web
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />django
<title>`title`</title>ide
</head>ui
<body>spa
<h1>hello `user`</h1>xml
</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'})
2、傳遞字典、列表變量
# 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})
3、傳遞類變量
# 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})