• 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>
    
  • 相关阅读:
    【codeforces 723F】stSpanning Tree
    struts2.0中struts.xml配置文件详解
    存储过程中调用JAVA程序段
    本不该逃避
    利用js实现对页面的自动刷新
    [转]从硬盘安装 RedHat Enterprise Linux Server 5 iso
    正则表达式使用
    利用XmlBean轻松读写xml(转)
    Struts2+Spring2+Hibernate3 web应用示例(七)
    在DWR中实现直接获取一个JAVA类的返回值的两种方法
  • 原文地址:https://www.cnblogs.com/yescarf/p/15081097.html
Copyright © 2020-2023  润新知