LoginSignup
31
39

More than 5 years have passed since last update.

Jade / pug を使ってjsonからページ大量生成

Last updated at Posted at 2016-12-08

EJS を使って json からページを生成するノウハウは見当たるのですが、
意外と Jade / pug で同じことをしようとすると手こずってしまったのでメモ。

やりたいことは、
1. 1つのテンプレートをベースに使う
2. json に生成したいページの情報をまとめる
3. (1)と(2) から静的 HTML を量産する

です。

実装

gulp-jade を使っています。

planData.json
[
  {
    "no": 1,
    "title": "北海道旅行",
    "text": "札幌、小樽、旭川のツアーはこちら"
  },
  {
    "no": 2,
    "title": "東北旅行",
    "text": "青森、秋田、岩手のツアーはこちら"
  },
  {
    "no": 3,
    "title": "関東旅行",
    "text": "群馬、栃木、茨城のツアーはこちら"
  }
]
task_jade.js
/**************************************************
 * modules load
 *************************************************/
const gulp   = require('gulp');
const fs     = require('fs');
const jade   = require('gulp-jade');
const data   = require('gulp-data');
const rename = require('gulp-rename');

/**************************************************
 * config
 *************************************************/
const template = './src/jade/planTemplate.jade';
const jsonPath = './src/json/planData.json';
const dest     = './dest/';

/**************************************************
 * task
 *************************************************/
gulp.task('jade', () => {
  const json = JSON.parse(fs.readFileSync(jsonPath));

  for (let key of json) {
    gulp.src(template)
        .pipe(rename(key.no + ".html"))
        .pipe(data (function (file){
          return {
            'fileName': file.path.split('/').pop().replace('.html', ''),
            'planList': json
          }
        }))
        .pipe(jade({
          pretty: true
        }))
        .pipe(gulp.dest(dest));
  }
});

planTemplate.jade
block vars
  - function getNo(){
  -   for(var i = 0; i < planList.length; i++){
  -     if(planList[i].no === Number(fileName)){
  -       return i;
  -     }
  -   }
  - }
  - const i = getNo()

html
  head
    meta(charset="utf-8")
    title プラン#{planList[i].no} - #{planList[i].title}

  body
    h1 #{planList[i].title}
    p #{planList[i].text}

タスク内で、テンプレートから json のデータを取り出すための key を 変数に入れています。

問題なければ、下記のHTML ファイルが生成されるはずです。

1.html
<head>
  <meta charset="utf-8"/>
  <title>プラン1 - 北海道旅行</title>
</head>
<body>
  <h1>北海道旅行</h1>
  <p>札幌、小樽、旭川のツアーはこちら</p>
</body>
2.html
<head>
  <meta charset="utf-8"/>
  <title>プラン2 - 東北旅行</title>
</head>
<body>
  <h1>東北旅行</h1>
  <p>青森、秋田、岩手のツアーはこちら</p>
</body>
3.html
<head>
  <meta charset="utf-8"/>
  <title>プラン3 - 関東旅行</title>
</head>
<body>
  <h1>関東旅行</h1>
  <p>群馬、栃木、茨城のツアーはこちら</p>
</body>

2017/01/12 追記:
pug でも同様に量産できます!

31
39
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
31
39