このページを翻訳

Express でテンプレートエンジンを使用する

template engine を使用すると、アプリケーションで静的なテンプレート ファイルを使用できます。 template engine を使用すると、アプリケーションで静的なテンプレート ファイルを使用できます。 実行時に、テンプレートエンジンはテンプレートファイルの 変数を実際の値に置き換えます。 をクリックして、テンプレートをクライアントに送信する HTML ファイルに変換します。 このアプローチにより、HTML ページのデザインが容易になります。このアプローチにより、HTML ページのデザインが容易になります。

The Express application generator uses Pug as its default, but it can generate apps configured for Handlebars-compatible engines such as hbs, EJS, among others.

For apps created by the generator, these settings are added to the generated app.js. For apps you create without the generator, set the following application setting properties yourself:

  • views テンプレートファイルがあるディレクトリ。例: app.set('views', './views') 。デフォルトはアプリケーションのルートディレクトリにある views ディレクトリです。
  • viewengine を使用するテンプレートエンジン。 viewengine を使用するテンプレートエンジン。 たとえば、Pugテンプレートエンジンを使用するには、app.set('view engine', 'pug')を使います。

Then install the corresponding Express-compatible template engine npm package; for example to install Pug:

Terminal window
npm install pug --save

Pug のような Express 準拠のテンプレートエンジンは、 __express(filePath, options, callback) という名前の関数、 res.render() がテンプレートコードのレンダリングを呼び出す をエクスポートします。

一部のテンプレートエンジンはこの規約に従っていません。一部のテンプレートエンジンはこの規約に従っていません。 @ladjs/integrate ライブラリは、一般的な Node.js テンプレートエンジンのすべてをマッピングすることによって、この規則に従っており、したがって、Express 内でシームレスに動作します。 For example, install hbs or any other Express-compatible Handlebars view engine instead of the raw handlebars package by itself.

ビューエンジンが設定された後、アプリケーションにエンジンを指定したりテンプレートエンジンモジュールをロードしたりする必要はありません。 Express はモジュールを内部的にロードします。例:

app.set('view engine', 'pug');

次に、viewsディレクトリにindex.pugという名前のパグテンプレートファイルを作成します。

html
head
title= title
body
h1= message

index.pug ファイルをレンダリングするルートを作成します。 index.pug ファイルをレンダリングするルートを作成します。 If the view engine property is not set, you must specify the extension of the view file. そうでなければ、それを省略することができます。

app.get('/', (req, res) => {
res.render('index', { title: 'Hey', message: 'Hello there!' });
});

ホームページへのリクエストを行うと、 index.pug ファイルは HTML としてレンダリングされます。

ビューエンジンキャッシュはテンプレートの出力の内容をキャッシュせず、元のテンプレート自体のみキャッシュします。 キャッシュがオンの場合でも、ビューはリクエストごとに再レンダリングされます。 The view is still re-rendered with every request even when the cache is on.