1)当传入对象是类实例时,通过 键.类属性 的形式在HTML中调用,view.py代码如下
1 class Person(): 2 username='李四' 3 4 def index(request): 5 p = Person() 6 context = { 7 'username':p 8 } 9 return render(request, 'index.html', context=context)
index.html 代码如下
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>模板渲染</title> 6 </head> 7 <body> 8 {{ username.username }} 9 </body> 10 </html>
2)当传入对象是字典时,view.py代码如下
1 def index(request): 2 context = { 3 'username':'李梅' 4 } 5 return render(request, 'index.html', context=context)
index.html 代码如下
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>模板渲染</title> 6 </head> 7 <body> 8 {{ username }} 9 </body> 10 </html>
3)当传入是嵌套字典时,view.py代码如下
1 def index(request): 2 context = { 3 'username':{ 4 'first':'张三', 5 'second':'李四', 6 'keys':'王五' 7 } 8 } 9 return render(request, 'index.html', context=context)
index.html 代码如下
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>模板渲染</title> 6 </head> 7 <body> 8 {{ username.first }} 9 </body> 10 </html>
4)当传入的是列表或者元组时,两种的用法一样,view.py代码如下
1 def index(request): 2 context = { 3 'username':['lisi','caocao','huangzhong','likui'] 4 } 5 return render(request, 'index.html', context=context)
index.html 代码如下
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>模板渲染</title> 6 </head> 7 <body> 8 {{ username.0 }} 9 {{ username.1}} 10 </body> 11 </html>