只需要记两种特殊符号:
{{ }}
和 {% %}
变量相关的用{{}}
,逻辑相关的用{% %}
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
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 的模板语法取值,只能使用句点取值方式,即.
的方式取值,不论是索引还是键,都只能用.
的方式取到