LoginSignup
8
9

More than 5 years have passed since last update.

EJS で記事一覧みたいなのを外部ファイル化してループする

Last updated at Posted at 2016-02-12

サンプルファイル
https://github.com/shimakyohsuke/gulp-ejs-filesystem

取り急ぎ社内説明用に投稿

package.json
{
  "devDependencies": {
    "gulp": "^3.9.0",
    "gulp-ejs": "^2.0.0",
    "gulp-plumber": "^1.1.0",
    "fs": "0.0.2"
  }
}
gulpfile.js
'use strict';

var gulp = require('gulp');
var ejs = require('gulp-ejs');
var plumber = require('gulp-plumber');
var fileSystem = require('fs');

gulp.task('ejs', function () {
    return gulp.src('./src/ejs/*.ejs')
        .pipe(plumber())
        .pipe(ejs(
            {
                config: JSON.parse(fileSystem.readFileSync('./data/config.json')),
                page: JSON.parse(fileSystem.readFileSync('./data/page.json')),
                loop: require('./data/loop.js')
            },
            {
                ext: '.html'
            }
        ))
        .pipe(gulp.dest('./dist/'));
});
/data/config.json
{
    "siteTitle": "siteTitle"
}
/data/page.json
{
    "hoge": {
      "headline": "hogemoge"
    }
}
/data/loop.js
module.exports = [
    {
        "tagline": "tagline",
        "article": "article"
    },
    {
        "tagline": "tagline2",
        "article": "article2"
    }
];
/src/ejs/index.ejs
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title><%= page.hoge.headline %> | <%= config.siteTitle %></title>
  </head>
  <body>
    <h1><%= page.hoge.headline %></h1>
<% loop.forEach(function(data){ %>
    <div class="article">
      <h2><%= data.tagline %></h2>
      <p><%= data.article %></p>
    </div>
<% }); %>
  </body>
</html>

$ gulp ejs

/dist/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>hogemoge | siteTitle</title>
  </head>
  <body>
    <h1>hogemoge</h1>

    <div class="article">
      <h2>tagline</h2>
      <p>article</p>
    </div>

    <div class="article">
      <h2>tagline2</h2>
      <p>article2</p>
    </div>

  </body>
</html>
8
9
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
8
9