【Django】HTMLを分割できるincludeタグの使い方

※本サイトにはプロモーション・広告が含まれています。

(最終更新月:2021年11月)

「ゴチャゴチャしてきたHTMLファイルを整理したい!」

「何度も使うHTMLコードを別ファイルに保存したい!」

というDjango初学者の方へ向けた記事となります

当記事を通じて、

  • 別HTMLファイルを読み込む「include」タグを使う方法

について解説していきます

筆者プロフィール

筆者プロフィールアイコン

【現職】プロダクトマネージャー

【副業】ブログ(月間17万PV)/YouTube/Web・アプリ制作

「プログラミング × ライティング × 営業」の経験を活かし、30後半からのIT系職へシフト。当サイトでは、実際に手を動かせるWebアプリの開発を通じて、プログラミングはもちろん、IT職に必要な情報を提供していきます。

【当ブログで紹介しているサイト】

当サイトチュートリアルで作成したデモ版日報アプリ

Django × Reactで開発したツール系Webアプリ

✔人に見せても恥ずかしくないコードを書こう

「リーダブルコード」は、わかりやすく良いコードの定義を教えてくれる本です。

  • 見るからにきれいなコードの書き方
  • コードの分割方法
  • 変数や関数の命名規則

エンジニアのスタンダートとすべき基準を一から解説しています。

何回も読むのに値する本なので、ぜひ手にとって読んでみてください。

別ファイルを読み込む「include」タグ

「include」タグを使って、別のHTMLファイルを読み込むことができます

読み込みたい箇所で、

{% include “templatesフォルダ以下のパス” %}

を記述することで対象のファイルをそのまま読み込むことが可能です

開発中の日報アプリでのコード例を見てみましょう!

分割元のベーステンプレート

今回、ベースとしているHTMLテンプレートがゴチャゴチャしてきましたので、別ファイルに保存し、整理していきたいと思います

✔src > templates > base.html

<!doctype html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.1/font/bootstrap-icons.css">
    {% load static %}
    <link rel="stylesheet" href="{% static 'css/footer.css' %}">
    <title>{% block title %}{% endblock %}</title>
  </head>
  <body>
    <nav class="navbar navbar-dark bg-primary">
      <div class="container-fluid">
        <div>
          <a class="navbar-brand" href="#">
              <i class="bi bi-bootstrap-fill" style="font-size: 2rem;"></i>
          </a>
        </div>
        <div class="flex-grow-1" style="max-width:500px;">
          <form class="d-flex" method="GET">
            <input class="form-control me-2" type="search" placeholder="検索..." aria-label="Search" name="search">
            <button class="btn btn-outline-light" type="submit">search</button>
          </form>
        </div>
        <div class="text-light nav-item dropdown">
            <a class="nav-link dropdown-toggle text-light" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
              ユーザー名
            </a>
            <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
              <li><a class="dropdown-item" href="#">アカウント設定</a></li>
              <li><hr class="dropdown-divider"></li>
              <li><a class="dropdown-item" href="#">ログアウト</a></li>
            </ul>
        </div>
      </div>
    </nav>
    {% block content %}{% endblock %}
    <footer class="bg-primary">
      <div id="footer-logo">
      <a href="#">
        <i class="bi bi-bootstrap-fill footer-logo" style="font-size: 3rem;"></i>
      </div>
      </a>
      <div class="footer-content">
          <div>
              <a href="#">
                  プライバシーポリシー
              </a>
          </div>
          <div>|</div>
          <div>
              <a href="#">
                  利用規約
              </a>        
          </div>
          <div>|</div>
          <div>
              <small>Copyright &copy; 2021 yulikepython</small>
          </div>
      </div>
    </footer>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
  </body>
</html>

こちらのコードを一部、以下のファイルに分けていきます。

  1. nav.html
  2. footer.html
  3. css.html
  4. js.html

分割先1:nav.html

✔src > templates > nav.html

<nav class="navbar navbar-dark bg-primary">
  <div class="container-fluid">
    <div>
      <a class="navbar-brand" href="#">
          <i class="bi bi-bootstrap-fill" style="font-size: 2rem;"></i>
      </a>
    </div>
    <div class="flex-grow-1" style="max-width:500px;">
      <form class="d-flex" method="GET">
        <input class="form-control me-2" type="search" placeholder="検索..." aria-label="Search" name="search">
        <button class="btn btn-outline-light" type="submit">search</button>
      </form>
    </div>
    <div class="text-light nav-item dropdown">
      <a class="nav-link dropdown-toggle text-light" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
            ユーザー名
      </a>
      <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
        <li><a class="dropdown-item" href="#">アカウント設定</a></li>
        <li><hr class="dropdown-divider"></li>
        <li><a class="dropdown-item" href="#">ログアウト</a></li>
      </ul>
    </div>
  </div>
</nav>

分割先2:footer.html

✔src > templates > footer.html

<footer class="bg-primary">
  <div id="footer-logo">
    <a href="#">
        <i class="bi bi-bootstrap-fill footer-logo" style="font-size: 3rem;"></i>
    </a>
  </div>
  <div class="footer-content">
      <div>
          <a href="#">
              プライバシーポリシー
         </a>
      </div>
      <div>|</div>
      <div>
          <a href="#">
              利用規約
          </a>        
      </div>
      <div>|</div>
      <div>
          <small>Copyright &copy; 2021 yulikepython</small>
      </div>
  </div>
</footer>

分割先3:css.html

✔src > templates > css.html

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.1/font/bootstrap-icons.css">
{% load static %}
<link rel="stylesheet" href="{% static 'css/footer.css' %}">

分割先4:js.html

✔src > templates > js.html

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>

分割後のベーステンプレート「includeを使う」

HTMLの分割が完了したら、あとはそのファイルをベーステンプレートで読み込んでいきます。

✔src > templates > base.html

<!doctype html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    {% include "css.html" %}
    <title>{% block title %}{% endblock %}</title>
  </head>
  <body>
    {% include "nav.html" %}
    {% block content %}{% endblock %}
    {% include "footer.html" %}
    {% include "js.html" %}
  </body>
</html>

ずいぶんとすっきりしました!

まとめ

他のHTMLファイルを読み込むには、以下を記述。

{% include “templates以下のパス” %}

ファイルを分割しておけば、編集箇所が見つけやすくなります。

うまく活用しましょう。

さて、現状ナビゲーションバー、フッターで使っているロゴはBootstrapのアイコンになっています

✔ナビゲーションバー

✔フッター

このままだとオリジナル感の出にくいサイトになってしまいますので、次回はオリジナルなロゴ(背景透過)を作成する便利ツールのご紹介をしていきます。

タイトルとURLをコピーしました