0

I have a nodejs/express application. I use jade template system for my templates. When I get template it assembles every time. But I want to increase performance by compiling it. Is it possible in express?

4

1 に答える 1

2

はい。appすべてのテンプレートをコンパイルしてメモリに残す、ロード時 (つまり、express の宣言時) に実行される関数を作成できます。

これを例にとります:

/**
 * @param   {Object}  app
 *
 * @api     private
 *
 * @summary Compiles the partial dashboard templates into memory
 *          enabling the admin controller to send partial HTMLs
 */
function compileJadeTemplates (app) {
  var templatesDir = path.resolve(
    app.get('views')
   , 'partials'
   );

  var templateFiles
    , fn
    , compiledTemplates = {};

  try {
    templateFiles = fs.readdirSync(templatesDir);
    for (var i in templateFiles) {
      fn = jade.compile(
            fs.readFileSync(path.resolve(templatesDir, templateFiles[i])));
      compiledTemplates[templateFiles[i]] = fn;
    }
    app.set('dashboard-templates', compiledTemplates);
  } catch (e) {
    console.log('ERROR');
    console.log('---------------------------------------');
    console.log(e);
    throw 'Error on reading dashboard partials directory!';
  }

  return app;
}

次のように、expressJS コントローラー関数でテンプレートを呼び出します。

/**
 * @param   {String}  req
 * @param   {Object}  res
 * @param   {Object}  next
 *
 * @api     public
 *
 * @url     GET       /admin/dashboard/user_new
 *
 * @summary Returns HTML via AJAX for user creation
 */
controller.newUser = function (req, res, next) {
  var compiledTemplates = app.get('dashboard-templates');    
  var html = compiledTemplates['_user_new.jade']({ csrf : req.session._csrf});
  return res.send({ status : 'OK', message : html});
}

この場合、htmlAJAX 経由で送信しています。アプリケーションによって追加されます。あなたがそれをしたくない場合。次の関数を使用して html を送信できます。

res.write(html);
return res.end();
于 2013-02-26T13:35:11.647 に答える