0

我有一个 nodejs/express 应用程序。我为我的模板使用了翡翠模板系统。当我得到模板时,它每次都会组装。但我想通过编译来提高性能。快递可以吗?

4

1 回答 1

2

是的。您可以构建一个在加载时执行的函数(即在appexpress 中的声明处),它将编译所有模板并将它们留在内存中:

以此为例:

/**
 * @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});
}

在这种情况下,我html通过 AJAX 发送;由应用程序附加。如果您不想这样做。您可以使用以下功能发送 html:

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