错误:未指定默认引擎,也未提供扩展名(ExpressJs和nunjucks)

时间:2019-03-24 14:42:19

标签: node.js express nunjucks

我正试图在Expres js中使用nunjucks模板引擎。页面显示正确,但控制台上出现错误。 Error: No default engine was specified and no extension was provided.

来自nunjucks文档

var app = express();

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

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

我跟踪了错误,发现它来自at new NunjucksView (C:\Users\future\Desktop\New folder (2)\node_modules\nunjucks\src\express-app.js:13:13)

nodemodules/nunjucks/src/express-app.js中引发错误

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

据我所知,这意味着未设置defaultEngine。

Github Repo


如何 在使用nunjucks时设置默认模板引擎。

1 个答案:

答案 0 :(得分:1)

您应该将express的默认view engine设置为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')
});

如果您想更改模板/视图扩展名,则可以这样更改:

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

,然后重命名模板/视图index.nunj