Python Django view render返回变量

作者 夜狼荼 2019年05月16日 01:59 阅读 1050

两种返回值的方法

1. 手动字典输出

def index(request):
    t=time.ctime
return render(request,'index.html',{'time':t})  # 在html文件中使用{{time}}调用 -->> time 为key名称

2. locals() 获取本地所有变量

def index(request):
    t=time.ctime
return render(request,'index.html',locals())  # 在html文件中使用{{t}}调用 -->>t为本地变量名称

####locals() python内置函数详解

locals() 函数会以字典类型返回当前位置的全部局部变量。

返回值:返回字典类型的局部变量

实例:

>>>def runoob(arg):    # 两个局部变量:arg、z
...     z = 1
...     print (locals())
..
>>> runoob(4)
{'z': 1, 'arg': 4}      # 返回一个名字/值对的字典

发表评论