node.js + express + ejs の基本型

事前準備
// node.js のインストール
$ yum install node
...
$ node -v
v8.17.0
// npm のインストール
$ yum install npm
...
$ npm -v
6.14.11
パッケージのインストール
// 作業ディレクトリの作成
$ mkdir node01
$ cd node01
// package.json の作成
$ npm init
This utility will walk you through creating a package.json file.
...
package name: (node02) sample // パッケージ名:sample
version: (1.0.0)
description:
entry point: (index.js) app.js // app.js にしておく
test command:
git repository:
keywords:
author: author
license: (ISC)
About to write to /home/vagrant/work/node01/package.json:
// express + ejs + bootstrap のインストール
$ npm install express ejs bootstrap --save
ディレクトリ階層
- /node_modules
- ...
- /public ← 新規作成
- /bootstrap ← /node_modules/bootstrap/dist をコピペ & リネーム
- /css
- bootstrap.min.css
- /js
- /css
- /bootstrap ← /node_modules/bootstrap/dist をコピペ & リネーム
- /routes ← 新規作成
- index.js
- /views ← 新規作成
- index.ejs
- item.ejs
- app.js ← 新規作成
- package-lock.json
- package.json
コード
メイン。
const express = require("express");
const app = express();
// ejs を利用する
app.set("view engine", "ejs");
// localhost:8080/static で /publicディレクトリ配下の静的ファイルを利用できるようにする
app.use("/static", express.static(__dirname + "/public"));
// ルーティング
app.use("/", require("./routes/index.js"));
// ポート:8080
app.listen(8080);
ルーティング。
const router = require("express").Router();
router.get("/", (req, res) => {
const data = {
title: "タイトル",
items: [
{ name: "ABC" },
{ name: "DEF" },
{ name: "GHI" }
]
};
// data を ejs に渡す
res.render("index.ejs", data);
});
module.exports = router;
ejs のメイン。"data" を受け取ってレンダリングしている。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サンプル</title>
<link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css"></link>
</head>
<body>
<div class="container">
<h1><%= title %> </h1>
<p>Node.js + express の基本型</p>
<%- include("item.ejs", items) %>
</div>
</body>
</html>
item のループ処理を外出ししている。
<ul>
<% for (let item of items) { %>
<li><%= item.name %></li>
<% } %>
</ul>