Django4全栈进阶之路14 template模板的基础模板

发布时间 2023-04-24 10:23:24作者: 城南城南

在 Django 中,我们可以使用模板继承来避免代码的重复。模板继承是指我们可以在一个模板中定义一些公共的 HTML 代码,然后在其他模板中继承这个基础模板,并根据需要添加或覆盖一些内容。

通常情况下,我们会定义一个名为 base.html 的基础模板,其中包含网站的公共结构和样式,例如页眉、页脚、导航栏等。然后,在其他模板中,我们可以使用 extends 指令来继承这个基础模板,并在 block 块中添加或覆盖一些内容。

例如,下面是一个简单的 base.html 模板:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
  <header>
    <h1>My Site</h1>
    <nav>
      <ul>
        <li><a href="{% url 'home' %}">Home</a></li>
        <li><a href="{% url 'about' %}">About</a></li>
        <li><a href="{% url 'contact' %}">Contact</a></li>
      </ul>
    </nav>
  </header>
  <main>
    {% block content %}
    {% endblock %}
  </main>
  <footer>
    <p>&copy; 2023 My Site</p>
  </footer>
</body>
</html>

在上面的模板中,我们定义了一个 title 块和一个 content 块。在 title 块中,我们使用了一个默认值 My Site,但是在其他模板中,我们可以通过覆盖 title 块来修改这个值。在 content 块中,我们使用了一个空块,但是在其他模板中,我们可以在这个块中添加内容。

例如,下面是一个简单的 home.html 和about.html模板,它继承了 base.html 模板,并在 content 块中添加了一些内容:

{% extends 'base.html' %}

{% block content %}
<h2>Welcome to My Site</h2>
<p>This is the home page.</p>
{% endblock %}
{% extends 'base.html' %}

{% block content %}
<h2>Welcome to My Site</h2>
<p>This is the about page.</p>
{% endblock %}

 

在上面的模板中,我们使用了 extends 指令来继承了 base.html 模板。在 content 块中,我们添加了一些 HTML 代码来显示欢迎信息和介绍信息。

使用模板继承可以让我们更轻松地维护网站的代码,减少代码的重复,并使网站的结构更加清晰易懂。

路由设置:

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('home/', views.home, name='home'),
    path('about/', views.about, name='about'),
    path('user_list/', views.user_list, name='user_list'),
    # ... 其他 URL 模式 ...
]

视图:

from django.contrib.auth.models import User
from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse


def index(request):
    return HttpResponse("Hello, world. You're at the index.")


def home(request):
    return render(request, 'home.html')
    # return HttpResponse("This is the home page.")

def about(request):
    return render(request, 'about.html')
    # return HttpResponse("This is the about page.")

def user_list(request):
    users = User.objects.all()
    context = {'title': 'user list', 'users': users}
    return render(request, 'myapp/user_list.html', context)