zoukankan      html  css  js  c++  java
  • Django中templates使用的补充

    Django中的模版的使用

    1、实例:查询用户信息,在页面显示,并隔行有底色

    test1/views文件

    def userinfo(request):
        if request.method=='GET':
            userinfos=[{'name':'ahaii','age':20},
                      {'name':'jack','age':23},
                      {'name':'tom','age':24},
                      {'name':'rain','age':226},
                      {'name':'rock','age':22},
                      {'name':'lily','age':21},
                      ]
            return render(request,'2.html',{'user_obj':userinfos})  #将userinfors以user_obj参数传递给模版2.html。

    test1/2.html文件

    
    
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    </head>
    <body>
    <ul>
    {% for user in user_obj %}
    {#user_obj变量是views中render过来的#}
    {% if forloop.counter|divisibleby:'2' %}
    {#forloop.conter记录for循环的次数,forloop.conter0是从0开始计数,forloop.conter是从1开始计数.divisibleby:'2'表示被2整除#}
    <li style="background: darkgray">name:{{ user.name}},age{{ user.age }}</li>
    {% else %}
    <li>name:{{ user.name}},age{{ user.age }}</li>
    {#无论列表还是字典,取值时都用'.'#}
    {% endif %}
    {% endfor %}

    </ul>
    </body>
    </html>

     2、模版的继承

    一个项目中由于页面比较多,而有些页面中头部和底部的内容都是一样的,因此该部分内容无需重写。将内容一样的页面继承已经写好的页面即可。

    父页面中,使用关键字 {% block name %}...{% endblock %} 来指定可以被子页面替换的内容。

    子页面中,使用关键字{% extends '父页面' %} 来指定将要继承的页面,使用关键字 {% block name %}...{% endblock %} 来指定替换的内容。

    继承语法 '{% extends '父页面' %}' 必须写在页面的顶部,并且一个页面只能继承一个模版。  

     3、模块引用

    在一些项目中,往往会有多处需要登陆。这样可以将登陆单独写在一个html中,页面中需要登陆时直接引用该html页面就可以了。页面中引用其它html页面使用关键字{% include'登陆.html' %}即可。

  • 相关阅读:
    yocto/bitbake 学习资源
    QEMU/KVM学习资源
    ubuntu 中创建和删除用户
    git 重命名本地和远程分支
    Ubuntu 上搭建 FTP 服务器
    gdb 常见用法
    git log 显示与特定文件相关的 commit 信息
    基于 qemu system mode 运行 arm 程序
    基于 qemu user mode 运行 aarch64 程序
    checking in(airport)
  • 原文地址:https://www.cnblogs.com/ahaii/p/5710607.html
Copyright © 2011-2022 走看看