Reputation: 105
I'm using the sails helper method sails.renderView
to render a view into a string that is then used in an email, like so:
sails.renderView('emails/booking', emailData, function (err, view) {
emailService.send(user.email, view);
});
Is it possible to specify a layout file when rendering a view in this way? I'm using ejs template engine.
It doesn't look like I can use the view config (config/views.js
) as it's route based.
I had a look at the render function in sails/lib/hooks/views/render.js
and it looked like the layout file to use could be passed in the options object but when I did, no view is returned.
Upvotes: 4
Views: 1515
Reputation: 5671
EDIT: Sorry I missed that this is being generated outside the regular request/response context. Answer changed to reflect that.
I had a poke through the sails code, particularly the render engine
/**
* sails.hooks.views.render(relPathToView, options, cb_view)
*
* @param {String} relPathToView
* -> path to the view file to load (minus the file extension)
* relative to the app's `views` directory
* @param {Object} options
* -> options hash to pass to template renderer, including locals and locale
* @param {Function} cb_view(err)
* -> called when the view rendering is complete (response is already sent, or in the process)
* (probably should be @api private)
* @api public
*/
... lots of code ...
// if local `layout` is set to true or unspecified
// fall back to global config
var layout = options.layout;
if (layout === undefined || layout === true) {
layout = sails.config.views.layout;
}
Turns out you can set the layout as part of the options object you pass into sails.renderView()
So if you have an email template emailLayout.ejs
, you can use it by adding this line to you controller like so:
emailData.layout = '/emailLayout';
sails.renderView('emails/booking', emailData, function (err, view) {
emailService.send(user.email, view);
});
Big caveat, this explicitly only works for ejs
templates.
I haven't tested this, so let me know how it goes
Upvotes: 3