Pugのincludeを使用する際に、ルートパスで記述しようとして少し迷ったので、ルートパスでの記述方法をメモ。
サンプルコード
ディレクトリ構造は以下のようになっています。
- _pug
- _include
- _head.pug
- _header.pug
- _footer.pug
- index.pug
- _include
- gulpfile.js
ルートパスで記述したい場合、pugのoptionでルートに当たるディレクトリを指定する必要があるようです。
今回ルートに当たるディレクトリは_pugなので、basedir: ‘_pug’のように指定します。
gulpfile.js
var gulp = require('gulp'),
pug = require('gulp-pug');
gulp.task('pug', function() {
gulp.src(
['./_pug/**/*.pug', '!./_pug/**/_*.pug']
)
.pipe(pug({
pretty: true,
basedir: '_pug'
}))
.pipe(gulp.dest('./'))
});
これでincludeでルートパスが指定できるようになりました。
includeするpugファイル内は以下のようになっています。
_head.pug
head meta(charset="utf-8") link(rel="stylesheet", href="/css/style.css") title テストページ
_header.pug
header.header p.logo サイト名
_footer.pug
footer.footer p フッターです。
includeでルートパスを指定してみます。
index.pug
doctype html
html(lang="ja")
include /_include/_head.pug
body
include /_include/_header.pug
.contents
h1.ttl ページタイトル
include /_include/_footer.pug
HTMLにコンパイルすると、以下のように生成できました。
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/style.css">
<title>テストページ</title>
</head>
<body>
<header class="header">
<p class="logo">サイト名</p>
</header>
<div class="contents">
<h1 class="ttl">ページタイトル</h1>
</div>
<footer class="footer">
<p>フッターです。</p>
</footer>
</body>
</html>
【参考サイト】
コメントが承認されるまで時間がかかります。