zoukankan      html  css  js  c++  java
  • Django之前端模板继承

    在使用Django进行web开发时,往往会构造一个基础框架模板即base.html,而后在其子模板中对它所包含站点公用部分和定义块进行重载。

    首先创建一个base.html,源码为:

    [html] view plain copy
     
    1. <!DOCTYPE html>  
    2. <html>  
    3. <head>  
    4. <meta charset="UTF-8">  
    5. <title>{% block title %}{% endblock %}</title>  
    6. </head>  
    7. <body>  
    8.     <h1>My helpful timestamp site</h1>  
    9.     {% block content %}{% endblock %}  
    10.     {% block footer %}  
    11.     <hr>  
    12.     <p>Thanks for visiting my site.</p>  
    13.     {% endblock%}  
    14. </body>  
    15. </html>  

    这个叫做base.html的模板定义了一个简单的html框架文档,等会我们将在我们的站点中的页面使用它。子模板的作用就是重载、添加

    或保留那些块的内容。

    现在新建一个current_datetime.html模板来使用它:

    [html] view plain copy
     
    1. {% extends "base.html" %}  
    2. {% block title %}The current time{% endblock %}  
    3.   
    4. {% block content %}  
    5. <p>It is now {{current_date }}.</p>  
    6. {% endblock %}  

    再新建一个hours_ahead.html模板,源码为:

    [html] view plain copy
     
    1. {% extends "base.html" %}  
    2. {% block title %}Future time{% endblock %}  
    3.   
    4. {% block content %}  
    5. <p>In {{hour_offset }} hour(s),it will be {{next_time}}.</p>  
    6. {% endblock  %}  

    上面的部分非html标签等会再来解释它,现在在views.py中新建两个函数,index4,与index5,分别对应这两个模板。源码为:

    [python] view plain copy
     
    1. def index4(req,offset):  
    2.     offset=int(offset)  
    3.     next_time=datetime.datetime.now()+datetime.timedelta(hours=offset)  
    4.     return render_to_response("hours_ahead.html",{'hour_offset':offset,'next_time':next_time})  
    5.   
    6. def index5(req):  
    7.     now=datetime.datetime.now()  
    8.     return render_to_response('current_datetime.html',{'current_date':now})  

    在url中的配置为:

    [python] view plain copy
     
    1. url(r'^hours_ahead/(d{1,2}$)','blog.views.index4'),  
    2.     url(r'^current_datetime/$','blog.views.index5'),  

    现在启动服务器,在浏览器中查看效果,current_datetime.html为:

    hours_ahead.html中的效果为:

    如此两个html效果就显示出来了,同时也解释一下base.html中所起的作用,两个html中都使用了{% extends  %}标记,

    这个就是继承base.html中的内容,在使用{ % block XXXXX %}    {% endblock%}时,中间的内容便是插入在使用了base.html两个标签的

    中间,由此便极大的避免了代码的冗余。每个模板只包含自己独一无二的代码,无需多余的部分,而如果想要进行站点级的设计修改,仅需

    修改base.html,所有其他模板会立即反映出所做修改。

    上述,便是django之继承使用base.html模板。

  • 相关阅读:
    TranslateAnimation类:位置变化动画类
    android 启动第三方程序的代码(利用ComponentName)
    android背景选择器总结
    Spinner控件怎样在subActivity中使用
    Android 自定义 spinner (背景、字体颜色)
    AndroidWebView
    android gravity属性和weight属性
    android得到控件在屏幕中的位置
    解决android自定义标题充满的问题
    android中ListView的常用样式和属性
  • 原文地址:https://www.cnblogs.com/AmilyWilly/p/8477634.html
Copyright © 2011-2022 走看看