LoginSignup
1
1

HTML Template

Last updated at Posted at 2021-06-19

HTML Template

HTMLから別ファイルのテンプレートを読み込む最もシンプルな方法

  • 標準機能のみ
  • ライブラリ不要

HTML index.html

<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
<style>
body {
  width: 35em;
  margin: 0 auto;
  font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
<script defer="" src="loader.js"></script>
</head>
<body>
<h1>An error occurred.</h1>
<div>Sorry, the page you are looking for is currently unavailable.<br/>
Please try again later.</div>
<div id="template-header"></div>
<div><em>You be peaceful.</em></div>
</body>
</html>

HTML template template.html

<template id="inline-header">
  <div><h2>Internal server failed to eat spice curry.</h2><div>
</template>

JavaScript loader.js

class Loader {
  action() {
    const templates = document.querySelectorAll('div[id^=template-]');
    templates.forEach(template => {
      const inline = template.id.replace(/template/, 'inline');
      const fragment = document.querySelector(`#${inline}`);
      template.append(fragment.content);
    });
  }
  trigger() {
    fetch('template.html')
    .then(res => res.text())
    .then(content => {
      document.body.innerHTML += content;
      this.action();
    });
  }
}
window.addEventListener('DOMContentLoaded', () => new Loader().trigger());

このコードは、特定のアクションをトリガーとして実行される Loader クラスを定義しています。主な目的は、template.html からテンプレートを取得し、そのテンプレートをページの特定の場所に挿入することです。

説明

  1. Loader クラスは、テンプレートのロードとアクションの実行を担当します。

  2. action() メソッドは、テンプレートをロードし、特定の要素に挿入する処理を行います。

  3. querySelectorAll('div[id^=template-]') は、id 属性が "template-" で始まるすべての div 要素を取得します。つまり、id 属性が "template-" で始まる全ての div 要素がテンプレートの要素となります。

  4. templates.forEach(template => { ... }) は、取得したテンプレートの要素ごとに処理を行います。

  5. template.id.replace(/template/, 'inline') は、テンプレートの id 属性の "template" を "inline" に置き換えます。これにより、テンプレートの id から対応するインラインテンプレートの id を生成します。

  6. document.querySelector(#${inline}) は、生成されたインラインテンプレートの id を使用して、対応する要素を取得します。

  7. template.append(fragment.content) は、取得したインラインテンプレートの内容をテンプレート要素に追加します。

  8. trigger() メソッドは、テンプレートのロードとアクションの実行をトリガーします。

  9. fetch('template.html') は、"template.html" を取得するための Fetch API を使用します。

  10. .then(res => res.text()) は、レスポンスをテキスト形式で解析します。

  11. .then(content => { ... }) は、解析されたテキストコンテンツを取得し、次の処理を行います。

  12. document.body.innerHTML += content は、取得したテキストコンテンツを現在のページの HTML の末尾に追加します。

  13. this.action() は、テキストコンテンツの追加後に action() メソッドを呼び出し、テンプレートのロードと挿入を実行します。

  14. window.addEventListener('DOMContentLoaded', () => new Loader().trigger()) は、ページのコンテンツがすべて読み込まれた後に trigger() メソッドを呼び出します。これにより、テンプレートのロードと挿入が開始されます。

テンプレートがシンプルになることに焦点を当てました。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1