なんだかGoodVibes

日々の勉強メモです。

【Express入門】パーシャルの利用

こんにちは。今日はパーシャルの利用です。
パーシャルとは、テンプレートの一部を部品化して
後の変更をやりやすくすることです。
紹介するサンプルは以下です。
スタイルシートの紹介は今回も省略します。

  • sample.js(メインファイル)
  • index.ejs(表示用ファイル)
  • item.ejs(パーシャル用ファイル)

[sample.js]

var express = require('express');
var ejs = require('ejs');

var app = express();
app.engine('ejs', ejs.renderFile);
app.use(express.static('public'));

var data = {
    '001':'いちご',
    '002':'みかん',
    '003':'メロン',
};

// ----- トップページ -----
app.get('/', (req, res) => {
    var msg = 'パーシャル利用のサンプル。';
    res.render('index.ejs',
        {
            title:'Index',
            content:msg,
            data:data,
        });
});

var server = app.listen(ポート番号, () => {
    console.log('server start.');
});

[index.ejs]

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta http-equiv="content-type"
        content="text/html; charset=UTF=8">
    <title><%= title %></title>
    <link type="text/css" href="./style.css" rel="stylesheet">
</head>

<body>
    <head>
        <h1><%= title %></h1>
    </head>
    <div role="main">
        <p><%- content %></p>
        <p><table style="width: 50%;">
            <% for (var key in data) { %>
                <%- include('item', {key:key, val:data[key]}) %>
            <% } %>
        </table></p>
    </div>
</body>
</html>

[item.ejs]

<tr>
    <th><%= key %></th><td><%= val %></td>
</tr>

これで完了です。
index.ejsの以下の部分で、値をパーシャルに渡しています。

<%- include('item', {key:key, val:data[key]}) %>

Expressを利用しているかどうかで、以下の部分に大きな違いがあります。

// Express利用
 res.render('index.ejs',
        {
            title:'Index',
            content:msg,
            data:data,
        });
// Express利用なし
 res.render('index.ejs',
        {
            title:'Index',
            content:msg,
            data:data,
            filename:'item',
        });

Expressを使用している場合はパーシャルのファイルの名の指定は必要ありませんが
Expressを使用していない場合は、ファイルの指定が必要になります。
今回は以上です。