テンプレートの拡張 - Django

テンプレートの拡張とは

「 index.html 」を呼び出すと、title ブロックと content ブロックの内容を「 base.html 」に反映させた内容を表示します。

ディレクトリ構成

  • pythonApp
    • env
      • django_app
        • django_app
          • ...
        • hello
          • migrations
            • ...
            • templates
              • hello
                • base.html
                • index.html
          • __init__.py
          • admin.py
          • apps.py
          • models.py
          • tests.py
          • views.py
        • db.sqlite3
        • manage.py
      • ...

urls

pythonApp\env\django_app\django_app\urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('hello/', include(('hello.urls', 'hello')))
]

pythonApp\env\django_app\sub\urls.py

from django.urls import path
from .views import SubView

urlpatterns = [
  path('', SubView.as_view(), name='index'),
]

templates

pythonApp\env\django_app\hello\templates\hello\base.html

<!doctype html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>{% block title %}{% endblock %}</title>
  </head>
  <body>
    {% block content %}{% endblock %}
    <div id="footer">
      {% block footer %}{% endblock %}
    </div>
  </body>
</html>

pythonApp\env\django_app\hello\templates\hello\index.html

{% extends "hello/base.html" %}
{% block title %}ホーム{% endblock %}

{% block content %}
<h1>hello/index</h1>
{% endblock %}

{% block footer %}
<h1>footer</h1>
{% endblock %}