django-templates 模板变量

view视图中

from  django.http import HttpResponse
from django.template import loader
from  django.shortcuts import render


#模板中传入参数
def test_html(request):
    # t=loader.get_template('test.html')
    # html=t.render({'test':'11656565'})

    # return HttpResponse(html)

    return render(request,'test.html',{'test':16565446564})


#模板变量

def hello_world():
    return 'hello_world'

class Cat(object):

    def __init__(self,name) -> None:
       self.name=name
    def __str__(self) -> str:
        return self.name

    def say_name(self):
        return  'i am hungry '

def test_html_param(request):
    dic={}
    dic['str']='test'
    dic['int']=10
    dic['ls']=[1,2,'dasdas']
    dic['dict']={'a':9,'b':10}
    dic['func']=hello_world
    dic['class_obj']=Cat('kelly')


    return  render(request,'test_html.html',dic)


#总结:变量中的语法
"""
{{变量名}}
{{变量名.index}}
{{变量名.key}}
{{对象.方法}}
{{函数名}}



"""

html中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test_html_param</title>
</head>
<body>
    <h3>{{int}}</h3>
    <h3>{{str}}</h3>
    <h3>{{ls}}</h3>
    <h3>{{ls.0}}</h3>
    <h3>{{dict.a}}</h3>
    <h3>{{func}}</h3>
    <h3>{{class_obj}}</h3>
    <h3>{{class_obj.say_name}}</h3>
</body>
</html>

浏览器中显示结果


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test_html_param</title>
</head>
<body>
    <h3>10</h3>
    <h3>test</h3>
    <h3>[1, 2, &#39;dasdas&#39;]</h3>
    <h3>1</h3>
    <h3>9</h3>
    <h3>hello_world</h3>
    <h3>kelly</h3>
</body>
</html>
上一篇:python测试开发django-67.templates模板变量取值


下一篇:Django Template file 'fileName' not found less