Django学习笔记005——Templates的变量

在Templates中变量表示为:{{ a }} 
注意:变量要遵守标识符的命名规则,如果使用的变量不存在,将会插入一个空字符串 
在模板中还可以用点语法去访问对象中的属性。字典和类的属性的调用,也需要使用‘.’,而不是'[]' 
在模板中调用对象的方法与调用属性相同,不需要小括号,不允许传参 {{stu.say}}。

在views中render函数需要对context参数进行传参,传参为类似于字典类型

render函数的参数:render(request, template_name, context=None, content_type=None, status=None, using=None)

 举例:

 view.py

from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
class person():
    def __init__(self,name):
        self.name=name
person=person("tester")

def vartest(request):
    dict={"name":"tudou","age":30}
    context = {'name': 'Gregory',
               'person':person,
            'dict':dict}
    print(type(context))
    return render(request,"vartest.html",context=context)

templates

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
   {{ name }}
   {{ person.name }}
   {{ dict.name }}
</body>
</html>

运行结果:

猜你喜欢

转载自blog.csdn.net/yaoliuwei1426/article/details/82466409
今日推荐