今回、Djangoで共通部分の切り出しを行ってみたので投稿します。
下図の様に土台となるbase.htmlを作成し、その上でindex.htmlとabout.htmlが入れ替わるページを作って行こうと思います。
まずは、プロジェクトフォルダ内のurls.pyを編集します。
#プロジェクト名/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('app.urls')),
]
プロジェクトフォルダでの作業は以上です。
ここからはアプリフォルダでの作業になります。
アプリフォルダー内のviews.pyを編集します。
①IndexViewクラス → index.html
②AboutViewクラス → about.html
#アプリ名/views.py
from django.views.generic import TemplateView
class IndexView(TemplateView):
template_name = 'アプリ名/index.html'
class AboutView(TemplateView):
template_name = 'アプリ名/about.html'
アプリフォルダー内にurls.pyを作成し
編集します。
#アプリ名/urls.py
from django.urls import path
from .views import IndexView, AboutView
urlpatterns = [
path('', IndexView.as_view()),
path('about/', AboutView.as_view()),
]
from .views import IndexView, AboutViewで同じフォルダ内のviews.pyからIndexViewとAboutView二つのクラスを呼び出しています。ブラウザでlocalhost:8000とするとIndexViewクラスが呼ばれ、localhost:8000/aboutとするとAboutViewクラスが呼ばれるようにしています。今回はpathのname引数は必要ないので使用していません。
アプリフォルダー内にtemplatesフォルダを作成。その中にアプリ名フォルダを作成しbase.html、index.html、about.htmlを作成します。
#アプリ名/templates/アプリ名/base.html
<body>
{% block main %}{% endblock main %}
</body>
#アプリ名/templates/アプリ名/index.html
{% extents 'アプリ名/base.html' %}
{% block main %}
<h1>Index</h1>
{% endblock main %}
#アプリ名/templates/アプリ名/about.html
{% extents 'アプリ名/base.html' %}
{% block main %}
<h1>About</h1>
{% endblock main %}
ターミナルでpython manage.py runserverを実行してブラウザのアドレスバーにlocalhost:8000と入力すると「Index」が表示されます。また、localhost:8000/aboutと入力すると「About」が表示されます。 以上で共通部分の切り出しができました。 base.htmlはこのままで表示できますが、VSCodeのEmmetやBootstrapを使用する場合はbodyタグを見つけてその中にblockテンプレートタグを記載すれば大丈夫です。
次にリンクを備えたヘッダーを作成し、ついでにフッターも付けてみたいと思います。
_header.htmlと_footer.htmlを作成します。
#アプリ名/templates/アプリ名/_header.html
<ul>
<li>
<a href="/">Index</a>
</li>
<li>
<a href="/about">About</a>
</li>
</ul>
#アプリ名/templates/アプリ名/_footer.html
<p>footer</p>
base.htmlを修正します。
#アプリ名/templates/アプリ名/base.html
<body>
{% includ 'アプリ名/_navbar.html' %}
{% block main %}{% endblock main %}
{% includ 'アプリ名/_footer.html' %}
</body>
これで以下のようなリンクをクリックすると遷移できるページができました。
以上になります。
分かりにくい部分などありましたらお知らせ頂けると助かります。お知らせいただいた内容は公開されることはありません。どの記事から投稿されたかは分かるようにしています。