• python测试开发django(6)--模板中include使用


    前言

    当我们打开一个网站的时候,在打开不同的页面时候,会发现每个页面的顶部、底部内容都差不多,这样就可以把这些公共的部分,单独抽出来。

    类似于python里面的函数,把公共部分写成函数,然后调用就行了,这样就能实现代码的复用。django里面也有类似的功能,用include可以实现。

    公共内容

    如下图所示,网站的每个页面都有顶部导航,body正文,底部导航这三块内容

     一般头部和底部是不变的,变的只是body里面内容,这样把头部和底部单独抽出来

    xjyn/templates/top1.html单独拿出来

    <section>
        <h1>顶部导航</h1>
        <p>python自动化-武汉-会</p>
        <hr>
    </section>
    

     xjyn/templates/end1.html单独拿出来 

    <section>
        <br><br><br><br><hr>
        <h1>底部导航</h1>
        <p>底部一些友情链接啊,网站导航,版权啊</p>
    </section>
    

     include语法

    xjyn/templates/page1.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
    {% include 'top1.html' %}
    <section>
        <h1>body正文</h1>
        <p>正文内容</p>
    </section>
    {% include 'end1.html' %}
    
    </body>
    </html>
    

     xjyn/views.py视图函数

    from django.shortcuts import render
    from django.http import HttpResponse,Http404
    # Create your views here.
    
    def he(request):
        return render(request,"page1.html")
    

     urls.py添加访问路径

    #helloworld/helloworld/urls.py
    from django.conf.urls import url
    from django.urls import re_path,path
    from xjyn import views
    
    urlpatterns=[
        url('^home$',views.he),
    ]
    

     浏览器访问地址http://127.0.0.1:8000/home 就能看到效果了

    带参数

    公共部分top1.html和end1.html里面也可以传变量,如

    <section>
        <h1>顶部导航</h1>
        <p>python自动化-{{name}}</p>
        <hr>
    </section>
    

     对应视图函数

    def he(request):
        p={"name":"小白"}
        return render(request,"page1.html",p)
    

       

      

      

      

     

    越努力,越幸运!!! good good study,day day up!!!
  • 相关阅读:
    水洼,八连杀
    友链
    万能转换字符类型到int ,int到string,string到char or char *等等
    蓝桥杯模拟赛题
    2020 03 21
    2019 12 02 reading
    CentOS 7 定时计划任务设置
    xinted &telnet
    2019 12 02 section C one
    【暖*墟】#洛谷网课1.30# 树上问题
  • 原文地址:https://www.cnblogs.com/canglongdao/p/14094459.html
Copyright © 2020-2023  润新知