您的位置:首页 > 编程语言 > Go语言

Django学习3-模板中使用变量

2017-04-22 16:10 519 查看
Django可以动态向模板中传递变量,主要是以字典方式传递的,继续前面的test01工程。

首先,在模板中使用变量,是用{{变量名}},这样的方式使用的,传递是在views.py的处理函数return render_to_response('index.html',{})中,通过第二个参数传递的,这是上次的模板,没有使用变量,所以是一个空字典。

比如,模板改为:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Cotent-Type" content="text/html;charset=UTF-8"/>
<title>{{title}}</title>
</head>
<body>
<h1>holle world!</h1>
</body>
</html>
这里,title就是使用的变量,那么,在传递的时候,就要这样写return render_to_response('index.html',{'title':'mytest'})。

除此之外,这里还支持其它类型的变量作参数,包括字典,列表,元组,甚至是类对象,只是在使用的时候,写法不一样,比如,

from __future__ import unicode_literals

from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render_to_response
class Student():
def __init__(self,score):
self.score=score
def getScore(self):
return self.score

# Create your views here.
def index(req):
# return HttpResponse('<h1>holle world</h1>')
book=('python','c','java')
student=Student(99)
user={'name':'dyp','age':23,'sex':'male'}
return render_to_response('index.html',\
{'title':'mytest3','book':book,'user':user,'student':student})

这里我定义了一个类,一个元组,一个列表,并将它们作为参数传递进去,那么在模板中,我们就可以这样调用<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Cotent-Type" content="text/html;charset=UTF-8"/>
<title>{{title}}</title>
</head>
<body>
<h1>{{book.0}}</h1>
<h1>hello {{user.name}}</h1>
<h1>{{student.score}}</h1>
<h1>{{student.getScore}}</h1>
</body>
</html>
即通过变量名.的方式调用,对于列表和元组,.后跟下标,字典.后跟键,而对于类对象,可以访问它的成员变量和不带参数的成员函数。

好了,主要的就是知道传递的时候以字典传,调用的时候{{}}调用,就这样了,在前面的工程里试试吧。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  django python