我正试图在Expres js中使用nunjucks模板引擎。页面显示正确,但控制台上出现错误。
Error: No default engine was specified and no extension was provided.
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。
如何 在使用nunjucks时设置默认模板引擎。
答案 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