django模板继承

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

  • 继承关系如图
    django模板继承

代码体现template继承

django模板继承

关键字

- 预设片断模板- 留坑
{% 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")

访问测试

django模板继承

特殊情况

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

django模板继承

django模板继承

  • extend要放在第一行

模板继承
django模板继承

Django 中url补充以及模板继承

相关文章:

  • 2022-01-30
  • 2022-02-20
  • 2022-12-23
  • 2022-12-23
  • 2021-08-29
  • 2022-12-23
  • 2021-09-22
猜你喜欢
  • 2022-01-17
  • 2021-08-23
  • 2022-12-23
  • 2021-08-09
  • 2021-08-28
  • 2021-08-08
  • 2021-09-18
相关资源
相似解决方案