母版頁用於處理html頁面相同部分內容,避免在不同的頁面中重復出現
1、添加母版頁
再manage.py文件相同目錄下添加templates文件夾用於保存母版頁html文件
2、添加母版頁Base.html,html如下:
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title></title> </head> <body> <h1>這是模板頁</h1> {% block content%} {% endblock %} </body> </html>
使用 block進行占位
3、在具體頁面使用母版頁
{% extends 'Base.html' %}
{% block content%}
This is ChildPageContent
{% endblock %}
4、由於母版頁和子頁面不在同一個APP下,需要在主模塊的settings.py 文件里面進行路徑配置,在同一app下則不需要配置,
在TEMPLATES 下的DIRS里面配置母版頁所在路徑
具體配置如下:
TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': ['django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages',], }, },]
最終頁面效果如下: