LoginSignup
9
7

More than 5 years have passed since last update.

シンプルにEJSでページを量産する

Posted at

始めに

node.jsでページ量産と調べるとgulp+ejsって組み合わせがよく出てくるのですが、そもそもejs単体じゃだめなのかなーって思ってやってみたら出来たのでメモです。
gulpはグローバルとローカル両方にインストールが基本って聞いててそうなるとexe化して他の人にも使ってもらう時とかに面倒そうだなと思って省きたかったのです。

EJSインストール

npm install --save ejs

実装

メインの実装

index.js
const fs = require('fs');
const path = require('path');
const ejs = require('ejs');

const templatePath = 'template-sample.ejs'; //テンプレート
const dataPath = 'data-sample.json';  //差異データ

const outputPath = 'result/'; //出力先


const data = JSON.parse(fs.readFileSync(dataPath,'utf-8')).data;

data.forEach((item) => {

  ejs.renderFile(templatePath, item, (error,output) => {
    if(error){
      console.log(error);
    }else{
      fs.writeFileSync(path.join(outputPath,`${item.filename}.html`),output);
    }
  })

});

テンプレート例

template-sample.ejs
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title><%= title %></title>
</head>
<body>
  <p><%= body %></p>
</body>
</html>

json例

data-sample.json
{
  "data" : [
    {
      "filename":"output1",
      "title":"title1",
      "body":"body1"
    },
    {
      "filename":"output2",
      "title":"title2",
      "body":"body2"
    }
  ]
}

サンプルの結果

output1.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>title1</title>
</head>
<body>
  <p>body1</p>
</body>
</html>
output2.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>title2</title>
</head>
<body>
  <p>body2</p>
</body>
</html>

終わりに

結構簡単に出来たので仕事でもサクッと使えそうです。

9
7
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
9
7