ericf / express-handlebars

A Handlebars view engine for Express which doesn't suck.
BSD 3-Clause "New" or "Revised" License
2.31k stars 384 forks source link

Usage of _compileTempate #123

Open xeroxoid opened 9 years ago

xeroxoid commented 9 years ago

Hi! Excellent work with the library (I bet you hear it all the time).

I am trying to inline all the CSS with "juice" before I send out an email with ''nodemailer-express-handlebars". For that I am passing an express-handlebars instance to the nodemailer-express-handlebars and I got a hint from what was said here: https://github.com/ericf/express-handlebars/issues/39#issuecomment-26743921 to override _compileTemplate (previously compileTemplate) in order to do that. It does not seem to work though and I can't seem to find what the matter is. My code is as follows:


var nodemailer = require('nodemailer');
var expHbs = require('express-handlebars');
var nodemailerExpHbs = require('nodemailer-express-handlebars');
var juice = require('juice');

var expHbsInstance = expHbs.create(viewEngineOptions);
var compileTemplate = expHbsInstance._compileTemplate.bind(expHbsInstance);

var viewEngineOptions = {
  extname: '.hbs',
  layoutsDir: 'server/views/email/',
  defaultLayout: 'template',
  partialsDir: 'server/views/email/partials/',
  compilerOptions: {
    _compileTemplate: function(template, options) {
      return compileTemplate(template, options)
        .then(function(compiled) {
          return juice(compiled);
        });
    }
  }
};

var nodemailerExpHbsOptions = {
  viewEngine: expHbsInstance,
  viewPath: 'server/views/email/',
  extName: '.hbs'
};

var mailer = nodemailer.createTransport(sgTransport(sgOptions));

mailer.use('compile', nodemailerExpHbs(nodemailerExpHbsOptions));

mailer.sendTestEmail...........

Any hints would be awesome and sorry for opening an issue for this (I understand it is more of a question..)

ericf commented 9 years ago

I'm not sure what nodemailer-express-handlebars is… but move the _compileTemplate function directly to the instance; e.g.:

var exphbs = require('express-handlebars');

var hbs = exphbs.create({ /* options */ });
hbs._compileTemplate = function (template, options) {
    // Do something before.
    var compiled = this.handlebars.compile(template, options);
    // And/or do something after.
    return compiled;
};

You can call the default implementation of _compileTemplate if you want, or simply do what I did can call the Handlebars function directly.