Django day06 模版层(一) 变量和深度查询

一.模版语法之变量:

   1  - {{ 变量 }} ******重要*******{#这个相当于print了该变量#}

def index(request):
     name = 'prince'  #字符串
     age = 20  #数字类型
     ll = [233, 290, 'bp', 'dsb']  #列表
     tu = (1, 2, 3)  #元组
     dic = {'name': 'prince', 'age': 20, 'll': [1, 2, 3, 4]}
                
  # 在模板上相当于执行了test函数,打印了return的结果   def test(): print('prince') return 'bpcsmdj' # 类和对象 class Person(): # Person 人 def __init__(self, name, age): self.name = name self.age = age     def get_name(self): return self.name # 对象 @classmethod def cls_test(cls): return 'cls' @classmethod def stetic_test(cls): return 'stetic' # prince = Person('prince', 20) bastard = Person('bastard', 1000) Person_list = [prince, bastard] Person_dic = {'prince': prince, 'bastard': bastard} 在index.html文件中:    {#模板语言注释:前端看不到{##} {#这个相当于print了该变量#} <h1>模版语言之变量</h1> <p>字符串:{{ name }}</p> <p>数字类型:{{ age }}</p> <p>列表:{{ ll }}</p> <p>元组:{{ tu }}</p> <p>字典:{{ dic }}</p> {#只写函数名:相当于函数名(),执行该函数#} <p>函数:{{ test }}</p> <p>列表套对象:{{ Person_list }}</p> <p>字典套对象:{{ Person_dic }}</p> # return render(request, 'index.html', {'name': name}) # locals 会把index视图函数内(***全局变量是不可能的***)所有的变量当做参数传到index.html模版里面,打开连接时都能取到 return render(request, 'index.html', locals())

 

  2 - 深度查询:统一都用句点符 " . "     

在index.html文件中:
    <h1>深度查询</h1>
    {#深度查询:统一都用句点符 " . " #}
    <p>列表第0和第3个值:{{ ll.0 }} 和 {{ ll.3 }}</p>
    <p>字典取值:{{ dic.name }} 和 {{ dic.age }}</p>
        <p>对象取数据属性:{{ prince.name }}</p>
    <p>对象取绑定给对象的函数属性:{{ prince.get_name }}</p>
    {#取得对象都是它们的 return 返回值#}
    <p>对象取绑定给类的函数属性:{{ prince.cls_test }}</p>
    <p>对象取静态方法:{{ prince.static_test }}</p>
    <p>从对象列表中取出prince的年龄:{{ Person_list.0.age }}</p>
    {#拓展:字符串也可以用句点符来调用,但是不能调有参数的方法#} 
    <p>字符串的方法:{{ name.upper }}</p>    

 

posted @ 2018-11-09 21:07  温暖你的心  阅读(264)  评论(0编辑  收藏  举报