django模板继承

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' %}
{% load staticfiles %}

{% 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")

访问测试

特殊情况

  • base.html继承html和index.html继承html的区别(写的位置)

  • extend要放在第一行

模板继承

Django 中url补充以及模板继承

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值