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

问题描述 投票:1回答:1

我正在尝试使用带有Expres js的nunjucks模板引擎。页面呈现正确但控制台上出现错误。 Error: No default engine was specified and no extension was provided.

来自nunjucks docs

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时设置默认模板引擎。

node.js express nunjucks
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.