gulp-dataを使って、Pugで使うmetaの内容をjsonで管理するようにしてみます。
サンプルコード
gulp-pugとgulp-dataをインストールします。
npm install gulp-pug --save-dev npm install gulp-data --save-dev
gulpfile.jsに以下のように記述します。
var gulp = require('gulp'),
pug = require('gulp-pug'),
data = require('gulp-data');
gulp.task('pug', function() {
gulp.src(
['./_pug/**/*.pug', '!./_pug/**/_*.pug']
)
.pipe(data(function(file) {
// metaのjsonファイルを取得
var metaData = require('./_pug/data/meta.json');
// 対象のファイルパスを取得して、\を/に置換
var filePath = file.path.split('\\').join('/');
// 必要なファイルパス部分のみ取得
var fileName = filePath.split('_pug')[1].replace('.pug', '.html');
// jsonファイルから対象ページの情報を取得して返す
return metaData[fileName];
}))
.pipe(pug({
pretty: true,
basedir: '_pug'
}))
.pipe(gulp.dest('./'))
});
9~18行目がjsonファイルを扱う部分になります。
ディレクトリ構造を以下のようにして、実際に試してみます。
- _pug
- data
- meta.json
- about
- index.pug
- flow.pug
- index.pug
- no-meta.pug
- data
- gulpfile.js
meta.jsonに各ページのmeta情報を記述します。
meta.json
{
"/index.html": {
"title":"トップページ",
"description":"トップページです。",
"keywords":"トップ,トップ,トップ"
},
"/about/index.html": {
"title":"アバウトページ",
"description":"アバウトページです。",
"keywords":"アバウト,アバウト,アバウト"
},
"/about/flow.html": {
"title":"〇〇の流れページ",
"description":"〇〇の流れページです。",
"keywords":"〇〇の流れ,〇〇の流れ,〇〇の流れ"
}
}
_pugディレクトリ内の各Pugファイルを以下のように記述します。
Pug
doctype html
html(lang="ja")
head
title #{title}
meta(name="description" content=description)
meta(name="keywords" content=keywords)
body
HTMLにコンパイルすると、以下のように出力されました。
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<title>トップページ</title>
<meta name="description" content="トップページです。">
<meta name="keywords" content="トップ,トップ,トップ">
</head>
<body></body>
</html>
about/index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<title>アバウトページ</title>
<meta name="description" content="アバウトページです。">
<meta name="keywords" content="アバウト,アバウト,アバウト">
</head>
<body></body>
</html>
about/flow.html
<!DOCTYPE html>
<html lang="ja">
<head>
<title>〇〇の流れページ</title>
<meta name="description" content="〇〇の流れページです。">
<meta name="keywords" content="〇〇の流れ,〇〇の流れ,〇〇の流れ">
</head>
<body></body>
</html>
no-meta.htmlはjsonファイルに設定していないので、値が空になります。
no-meta.html
<!DOCTYPE html>
<html lang="ja">
<head>
<title></title>
<meta name="description">
<meta name="keywords">
</head>
<body></body>
</html>
【参考サイト】
コメントが承認されるまで時間がかかります。