码迷,mamicode.com
首页 > 其他好文 > 详细

[py]django模板继承

时间:2018-01-23 15:51:03      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:min   dmi   ase   tle   htm   markdown   ima   ott   div   

参考

django模板继承

  • 通过搞一个base.html
  • 这个base.html可以包含两类
    • block片断
    • 其他html
  • 然后index.html继承base.html

  • 继承关系如图
    技术分享图片

代码体现template继承

技术分享图片

关键字

- 预设片断模板- 留坑
{% block title %}
    默认标题
    {% endblock %}

- 预包含html文件
{% include 'nav.html' %}


- index.html继承base.html
{% extends 'base.html' %}

- index.html填坑
{% block content %}
    hello new content
{% endblock %}

项目代码体现

learn/templates/ - 其他一些小的html 如nav bottom tongji 等独立开来.

nav.html
<div>nav html</div>

tongji.html
<div>tongji html</div>

bottom.html
<div>bottom html</div>

learn/templates/base.html - 预设模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}
    默认标题
    {% endblock %}</title>
</head>
<body>
{% include 'nav.html' %}

{% block content %}
<div>这是默认的content</div>
{% endblock %}

{% include 'bottom.html' %}
{% include 'tongji.html' %}
</body>
</html>

learn/templates/index.html - 继承base.html,最终返回拼接好的index.html

{% extends 'base.html' %}
{% block title %}
hello new title
{% endblock %}

{% block content %}
    hello new content
{% endblock %}

url.py- 映射index的path

from learn import views

urlpatterns = [
    path('', views.index),
    path('admin/', admin.site.urls),
]

views.py - 返回index.html

def index(request):
    return render(request, "index.html")

访问测试

技术分享图片

[py]django模板继承

标签:min   dmi   ase   tle   htm   markdown   ima   ott   div   

原文地址:https://www.cnblogs.com/iiiiiher/p/8335684.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!