koajs / koa-hbs

Handlebars templates for Koa.js
MIT License
160 stars 43 forks source link

Rendering templates without outputting content #45

Closed AdamPflug closed 8 years ago

AdamPflug commented 8 years ago

Hi, this is a great module but I'm having some issues trying to use it to render HTML for an HTML email without actually sending it down to the client. Here is what I'm doing now (which seems really hacky):

var output = {};
yield this.render.call(output, 'email/confirmation', {
    subject: 'Email Subject'
});
var html = output.body;

This works OK if I'm doing this from within a request - but if I want to sends emails for some other reason (e.g. as a cron job) I don't have a request context anymore - so no this.render. I know I could just use the base handlebars package, but then I don't think I get the cool block/layout stuff you've added in.

Is there something I am missing that would make this easier?

Thanks!

jwilm commented 8 years ago

Is your cron job actually running Koa? Sounds like not. You can create a renderer that works outside of Koa like this (haven't ran this, but should be close).

let hbs = new Hbs();
hbs.configure({ /* your options here */ });
let email = {
  render: hbs.createRenderer();
};

yield email.render('template');

// email.body is now your rendered html
jwilm commented 8 years ago

Did you get this resolved?

AdamPflug commented 8 years ago

Yup, the createRenderer call to get a render function was all I needed, thanks!