Pugのincludeを使ってみる

Pugのincludeを使って、ファイルのインクルードをしてみます。

サンプルコード

今回はGulpを使って開発環境を作成しています。
Gulpを使った設定方法はこちらの記事を参考にしてください。

gulpfile.jsとディレクトリ構造は以下のようになっています。

gulpfile.js

var gulp = require('gulp'),
    pug  = require('gulp-pug');

gulp.task('pug', function() {
	gulp.src(
		['./_pug/**/*.pug', '!./_pug/**/_*.pug']
	)
	.pipe(pug({
		pretty: true
	}))
	.pipe(gulp.dest('./'))
});
  • _pug
    • _include
      • _head.pug
      • _header.pug
      • _footer.pug
    • index.pug
  • gulpfile.js

_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 フッターです。

index.pugで上記ファイルをインクルードさせてみます。

index.pug

doctype html
html(lang="ja")
  include _include/_head.pug
  body
    include _include/_header.pug
    .contents
      h1.ttl ページタイトル
    include _include/_footer.pug

以下のコマンドでHTMLにコンパイルしてみます。

gulp 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>

 

includeはpugファイルだけではなく、プレーンテキストやマークダウンでの記述も読み込むことができます。
例として、_includeディレクトリ内に以下3ファイルを追加してみます。

plaintext.txt

プレーンテキストです。

sample.css

h1 {
  color: red;
}

markdown.md

## マークダウンのサンプル

マークダウンのテストです。

マークダウンを読み込む場合、別途JSTransformerモジュールのmarkdown-itをインストールしないといけないようです。
jstransformer-markdown-itをインストールします。

npm install jstransformer-markdown-it --save-dev

追加した3ファイルをincludeしてみます。
マークダウンのみインクルードの記述がinclude:markdown-it となっているので注意してください。

index.pug

doctype html
html(lang="ja")
  include _include/_head.pug
  body
    style
      include _include/sample.css
    include _include/_header.pug
    .contents
      h1.ttl ページタイトル
      include _include/plaintext.txt
      include:markdown-it _include/markdown.md
    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>
    <style>h1 {
  color: red;
}
    </style>
    <header class="header">
      <p class="logo">サイト名</p>
    </header>
    <div class="contents">
      <h1 class="ttl">ページタイトル</h1>プレーンテキストです。<h2>マークダウンのサンプル</h2>
<p>マークダウンのテストです。</p>

    </div>
    <footer class="footer">
      <p>フッターです。</p>
    </footer>
  </body>
</html>

 

【参考サイト】

 

このエントリーをはてなブックマークに追加

関連記事

コメントを残す

メールアドレスが公開されることはありません。
* が付いている欄は必須項目です

CAPTCHA


コメントが承認されるまで時間がかかります。

2024年4月
 123456
78910111213
14151617181920
21222324252627
282930