今回はNode.jsで使えるHTMLのテンプレートエンジンPugを使います。PugはもともとJadeという名前でしたがバージョン2.0.0からPugに名前が変わっています。
Pugとは
HTMLのテンプレートエンジンで、Node.jsで使うことができます。
Pugの使い方
作業ディレクトリ作成
早速入門していきましょう。作業ディレクトリをつくります。今回はpug-sampleと名前をつけました。Pugを使うためにPugをインストールしています。
mkdir pug-sample cd pug sample npm init npm install pug
Pugのテンプレートファイルを作る
Pugのファイルを作成します。今回はindex.pugとします。拡張子はpugです。かわいいですね。
// index.pug
doctype html
html(lang="ja")
head
meta(charset="utf-8")
title Pug sample page
body
h1 Hello pug
p Pug is a terse and simple templating language with a
strong focus on performance and powerful features.
インデントでツリー構想を構築
PugではHTMLのツリー構造をインデントで表します。閉じタグで囲う必要がなく記述が減ります。要素名から半角スペースあけてテキストを記述することでテキストノードとなります。
属性は括弧で記述
lang属性やchaset属性を括弧で記述できます。これは直感的に記述することができますね。 たとえばformであればactionやmethodなど同じように記述でき、classやidは
section#idName p.className
のように記述します。
Pugのテンプレートを表示する
表示にはNode.jsを使います。過去にhttpモジュールで作成したサーバーを調整してテンプレートを表示します。
// index.js 'use strict';
const http = require('http');
const pug = require('pug');
const server = http.createServer((req, res) => {
res.writeHead(200, {
'Content-Type': 'text/plain; charset=utf-8'
});
res.write(pug.renderFile('index.pug', {}));
res.end();
});
const port = 8000;
server.listen(port, () => {
console.log(`Server listening on http://localhost:${port}`);
});
下記でPugを読み込んでいます。
const pug = require('pug');
そして下記でrenderFileメソッドでPugテンプレートを読み込んでいます。
res.write(pug.renderFile('index.pug', {}));
サーバーを起動してPugのテンプレートの表示確認
Pugのテンプレートを読み込む準備ができたのでサーバーを起動して表示を確認します。
node index.js
サーバーが起動したらhttp://localhost:8000にアクセスし、テンプレートで作成したHTMLが表示されているかを確認しましょう。
Pugのテンプレート内で変数を使う
テンプレートエンジン内で変数を扱うことができます。これもテンプレートエンジンを使うメリットの一つです。
Pugのテンプレートファイルを書き換える
// index.pug
doctype html
html(lang="ja")
head
meta(charset="utf-8")
title #{pageTitle}
body
h1 #{contentTitle}
p Pug is a terse and simple templating language with a
strong focus on performance and powerful features.
Pugのテンプレートで変数を展開するときは#{変数名}とします。変数はrenderFile関数の第二引数にオブジェクトで渡してあげます。
index.jsで変数を設定する
res.write(pug.renderFile('index.pug', {
pageTitle: 'Pug sample page',
contentTitle: 'Hello Pug!!'
}));
テンプレートエンジンでHTMLの構築が楽になります
Pugには記述の省略や変数など便利な機能があるので、Node.jsでHTMLを構築する必要がある場合はPugのようなテンプレートエンジンを使います。