LoginSignup
1
2

More than 3 years have passed since last update.

expressによるウェブページテンプレート化の手法(express-ejs-layoutsを使用)

Last updated at Posted at 2020-01-25

概要

Expressにおけるwebページのテンプレート化の方法をまとめてみる。
使用するパッケージは以下の通り。
・express
・express-ejs-layouts

作成するファイルは以下の通り。
(1) /main.js
テンプレート化に必要なパッケージの読み込み、レスポンスのロジックを実装

(2) /views/layout.ejs
テンプレートエンジンが使用するレイアウトのウェブページのテンプレート。このファイルでページのレイアウトとコンテンツの埋め込み箇所を定義する。

(3) /views/index.ejs
テンプレートエンジンがレイアウトに埋め込むファイル。
ここではindexのページを定義しているが、ユーザーのアクセスするパスに応じて他のejsファイルも作成する。

Step1. main.jsの実装

まず、以下のようにmain.jsを実装する。
(1) パッケージのインポート
以下3つの定数を定義する。

const express =require(“express”)
const layouts = require(“express-ejs-layouts”)
const app = express()

(2) view engineの指定
appに対して、view engineの属性設定。

app.set(“view engine”,”ejs”)

(3) リクエストパスに対するレスポンスロジックの実装
以下のようにrenderに/view/index.ejsのファイルをテンプレートとして読み込むことを指定する。拡張子指定不要。

app.get(“/”, (req, res) => {
    res.render(“index”)
})

Step2. layout.ejsの定義

layout.ejsはページ間で共通のコンテンツを定義する。
その上で、各ページ固有のコンテンツを埋め込む場所を定義する。

<html>
<head> ... </head>
<body> 
レイアウトのコンテンツを記載

<%- body %>

</body>
</html>

上記でも記載のあるように、以下の記述が各ページのコンテンツの埋め込み先になる。

<%- body %>

Step3. index.ejsの定義

index.ejsには、laytout.ejsの<%- body %>に埋め込むコンテンツを定義することになる。

<h1>これがhttp://xxxxxx.xx.xx/にアクセスした際に表示されるページのコンテンツ部分です</h1>

ポイントは、HTMLを記載しているのだが、お決まりのから始まるタグの記載をするのではなく、layout.ejsに埋め込まれることを想定したhtmlの記述をする必要がある。

1
2
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
2