Django 模板语法-传值、取值

只需要记两种特殊符号:

{{ }}{% %}

变量相关的用{{}},逻辑相关的用{% %}

1.1 模板语法传值

方式一:指名道姓传参数

render ( request, ‘网页’, {‘字段 1’: 值,‘字段 2’:值} )

views.py文件中

from django.shortcuts import render, HttpResponse, redirect

def index(request):
  	user_dict = {'name':'frank','age':18}
    response = render(request,'render_test.html', {'data':user_dict,'date':123})

    return response

render_test.html通过{{ 字段 }}拿值

<body>
    <div>data:{{ data }}</div>
    <div>date:{{ date }}</div>
</body>

方式二:使用locals()

将函数内部所有的变量名都传给网页,包括request

from django.shortcuts import render, HttpResponse, redirect

def index(request):
  	user_dict = {'name':'frank','age':18}
    response = render(request,'render_test.html', locals())
    
    return response

 

1.2 模板语法取值

python 常见的数据类型
def index(request):
  	f = 1.1
    inter = 1
    string = 'ttt'
  	listt = [1,2,3]
  	tuple1 = (1,2,33)
  	user_dict = {'name':'frank','age':18}
    se = {1,2,3,4}
    bol = True
    
    response = render(request,'render_test.html', locals())
    
    return response
<body>
  {{ f }}
  {{ inter }}
  {{ string }}
  {{ listt }}
  {{ tuple1 }}
  {{ user_dict }}
  {{ se }}
  {{ bol }}
</body>

 

函数类型传值
def index(request):
		def func():
      print('from func')
      return None
    
    response = render(request,'render_test.html', locals())
    
    return response
<body>
	{{ func }}
</body>

前端结果为:None

后端会打印:from func

所以,模板语法传入函数会自动运行函数,并且拿到函数的返回值

但是只针对无参函数,有参函数在前端是没有办法通过模板语法给后端传值的!!!


 

类与对象传值
def text(request):
  
    class cls(object):
        def get_obj(self):
            return 'from cls'

    obj = cls()

    response = render(request, 'test.html', locals())

    return response

在前端,模板语法与函数的类似—传入类名会加括号调用,返回一个实例化的对象

对于对象则可以 obj.属性 拿到对应的值

<body>
  {{ cls }}
  {{ obj.get_obj }}
</body>

 

注意事项

Django 的模板语法取值,只能使用句点取值方式,即.的方式取值,不论是索引还是键,都只能用.的方式取到


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值