app.engine(ext, callback)
メソッドを使用して独自のテンプレートエンジンを作成します。 ext
はファイルの拡張子を参照し、 callback
はテンプレートエンジンファンクションで、以下の項目を引数として受け付けます: ファイルの場所、オプションオブジェクト、コールバックファンクション。
次のコードは、 .ntl
ファイルをレンダリングするための非常にシンプルなテンプレートエンジンの実装の例です。
const fs = require('fs') // this engine requires the fs module
app.engine('ntl', (filePath, options, callback) => { // define the template engine
fs.readFile(filePath, (err, content) => {
if (err) return callback(err)
// this is an extremely simple template engine
const rendered = content.toString()
.replace('#title#', `<title>${options.title}</title>`)
.replace('#message#', `<h1>${options.message}</h1>`)
return callback(null, rendered)
})
})
app.set('views', './views') // specify the views directory
app.set('view engine', 'ntl') // register the template engine
アプリは .ntl
ファイルをレンダリングできるようになります。 views
ディレクトリに index.ntl
という名前のファイルを作成し、内容を以下のようにします。
#title#
#message#
次に、アプリに以下のルートを作成します。
app.get('/', (req, res) => {
res.render('index', { title: 'Hey', message: 'Hello there!' })
})
ホームへリクエストを行うと、 index.ntl
が HTML としてレンダリングされます。