このページを翻訳

Express 用テンプレートエンジンの開発

app.engine(ext, callback)メソッドを使用して、独自のテンプレートエンジンを作成します。 extはファイル拡張子を指し、callbackはテンプレートエンジン関数です。 は、次の項目をパラメータとして受け付けます。ファイルの場所、options オブジェクト、およびコールバック関数です。

以下のコードは、.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としてレンダリングされます。