Erik
Erik

Reputation: 14770

Is it possible to compile jade templates for production usage?

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?

Upvotes: 0

Views: 1380

Answers (1)

hhh
hhh

Reputation: 2769

Yes. You can build a function to be executed at loading time (i.e. at the app declarations in express), which will compile all your templates and leave them in memory:

Take this as an example:

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

Calling the templates in an expressJS controller function this way:

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

In this case, I'm sending the html via AJAX; to be appended by the application. In the event that you don't want to do that. You can send the html with these functions:

res.write(html);
return res.end();

Upvotes: 2

Related Questions