简体   繁体   中英

Node.js - Migrating from Swig to Nunjucks in Express

I have a Node.js app. I've been building this app for a while and it currently uses Swig as the view engine. I'm setting it as the view engine using the following code:

// Use swig.    
const swig = require('swig');
app.engine('html', swig.renderFile);
if (app.get('env') === 'development') {
  swig.setDefaults({ cache: false });
}

app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'html'); 

This has been working well. However, I have some downtime so I thought now would be a good time to migrate to Nunjucks . So, I replaced the above with:

// Use nunjucks.    
const nunjucks = require('nunjucks');
app.engine('html', nunjucks.renderFile);
if (app.get('env') === 'development') {
  nunjucks.setDefaults({ cache: false });
}
app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'html');    

When I start up my site, I now get an error. The error is:

    throw new Error('callback function required');
    ^

Error: callback function required
    at EventEmitter.engine (C:\MyProject\node_modules\express\lib\application.js:294:11)
    at EventEmitter.module.exports (C:\MyProject\src\index.js:16:9)
    at EventEmitter.configure
...

What am I doing wrong? What callback is being sought after? I know I'm going to have some syntactical errors once I start using the Nunjucks engine. However, I'm just trying to figure out how to get the Nunjucks engine loaded.

Templating engines usually have their own method of configuration. For Nunjucks, you should use this:

const nunjucks = require('nunjucks');

nunjucks.configure('views', {
  express : app,
  noCache : app.get('env') === 'development',
  ...
});

Documentation here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM