Search code examples
node.jsexpressnunjucks

Error: No default engine was specified and no extension was provided (ExpressJs & nunjucks)


I am trying to use nunjucks templating engine with Expres js. The page is rendered correctly but error appears on console. Error: No default engine was specified and no extension was provided.

from nunjucks docs

var app = express();

nunjucks.configure('views', {
    autoescape: true,
    express: app
});

app.get('/', function(req, res) {
    res.render('index.html');
});

I traced the error and found it comes form at new NunjucksView (C:\Users\future\Desktop\New folder (2)\node_modules\nunjucks\src\express-app.js:13:13)

In nodemodules/nunjucks/src/express-app.js throw error

    if (!this.ext && !this.defaultEngine) {
      throw new Error('No default engine was specified and no extension was provided.');
    }

Which means as I understand that defaultEngine is not set.

Github Repo


How to set default template engine while using nunjucks.


Solution

  • You should set the default view engine for express to be the same extension known/rendered by nunjucks

    const express =  require('express');
    const nunjucks = require('nunjucks');
    
    const app = express();
    
    // set default express engine and extension
    app.engine('html', nunjucks.render);
    app.set('view engine', 'html');
    
    // configure nunjucks engine
    nunjucks.configure('views', {
        autoescape: true,
        express: app
    });
    
    app.get('/', function(req, res) {
        res.render('index');
    });
    
    app.listen(9090, () => {
      console.log('http://localhost:9090')
    });
    

    if you want to change templates/views extension, you can change it like that:

    app.engine('nunj', nunjucks.render);
    app.set('view engine', 'nunj');
    

    and then rename your templates/views index.nunj