Codebling
Codebling

Reputation: 11382

Is it possible to use multiple template engines in Sails.js?

Express

In vanilla Express.js, the following code works nicely.

var app = require('express')();

app.get('/jade', function(req, res) {
  res.render('slash.jade');
});

app.get('/ejs', function(req, res) {
  res.render('slash.ejs');
});

app.listen(1338);

As long as the modules are present in node_modules, both templates are rendered by the appropriate engines.

You can also specify a default engine like so:

app.set('view engine', 'haml');
app.get('/', function(req, res) {
  res.render('slash'); //looks for slash.haml in views directory
});

In Express, the default view engine is only used when the extension is omitted.

Sails

In Sails.js, it seems like the engine specified config/view.js is the only engine ever used.

If I try to specify the extension directly, I get the following error:

error: Ignoring attempt to bind route (/barn) to unknown view: barn.jade

Is it possible to use different view engines without a large amount of voodoo in Sails?

Upvotes: 5

Views: 476

Answers (1)

Glen
Glen

Reputation: 1178

The short and most accurate answer is no.

Out of poor boredom, I took a look at this question and done a bit of a deep dive into the views engine code in sails. If interested you can also find these files in your sails project by going to the directory:

node_modules\sails\lib\hooks\views

What you will find, is sails out of the box, is set up to use one view engine only. In the above directory, you will find a file called configure.js, this is where the logic behind setting a custom view engine happens.

Here is a snippet from the code

// Normalize view engine config and allow defining a custom extension
if (_.isString(sails.config.views.engine)) {
    var viewExt = sails.config.views.extension || sails.config.views.engine;
    sails.config.views.engine = {
          name: sails.config.views.engine,
          ext: viewExt
    };
}

// Get the view engine name
var engineName = sails.config.views.engine.name || sails.config.views.engine.ext;

Unfortunately, there is no looping through to set multiple engines. Sails simply uses the engine passed in the parameter sails.config.views.engine and goes from there.

Upvotes: 1

Related Questions