11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

gulp+ejs:条件分岐で内容の違う2つのHTMLを生成してみる

Last updated at Posted at 2015-02-16

例:
タスクstep1はtrueをejsテンプレートに渡しstep1.htmlを生成する。
タスクstep2はfalseをejsテンプレートに渡しstep2.htmlを生成する。
※node.jsとgulpは既にインストール済みとしてインストール方法は省略します。

#gulp-ejsのインストール

npm install --save-dev gulp-ejs

#gulpfile.jsの記述例

gulpfile.js
var steps = {
    step1:['step1',true],
    step2:['step2',false]
};
for (var key in steps){
    (function(key) {
        gulp.task(steps[key][0], function() {
            gulp.src("./*.ejs")
            .pipe(ejs({flg:steps[key][1] }))
            .pipe(rename(steps[key][0]+".html"))
            .pipe(gulp.dest("./"))
        });
    })(key);
}

//ファイルの監視
gulp.task("default",['server'], function() {
    gulp.watch(["./**/*.ejs"], ["step1","step2"]);
});

#ejsファイルの記述例

  • <%= 値 %> :HTMLをエスケープ処理する
  • <%- 値 %> :HTMLをエスケープ処理しない
sample.ejs
<%
var step;
var code;

if(flg){
	step = "steps01";
	code = '<p><a href="#">次へ</a></p>';
}else{
	step = "steps02";
	code = '<p>完了</p>';
}%>
<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="utf-8">
</head>
<body>
<h1 class="<%= step %>"><%= step %></h1>
<%- code %>
</body>
</html>

#生成されたコード

step1.html
<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="utf-8">
</head>
<body>
<h1 class="steps01">steps01</h1>
<p><a href="#">次へ</a></p>
</body>
</html>
step2.html
<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="utf-8">
</head>
<body>
<h1 class="steps02">steps02</h1>
<p>完了</p>
</body>
</html>
11
11
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
11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?