【问题标题】:Error: No default engine was specified and no extension was provided (ExpressJs & nunjucks)错误:未指定默认引擎且未提供扩展名(ExpressJs 和 nunjucks)
【发布时间】:2019-03-26 20:44:54
【问题描述】:

我正在尝试将 nunjucks 模板引擎与 Express js 一起使用。页面正确呈现,但控制台上出现错误。 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】:

您应该将 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

【讨论】:

  • 它有效。但它抛出Error: template not found: error.html。我在视图目录中添加了 error.html 文件并修复了错误。@Ahmed Ayoub 我没有尝试更改模板/视图扩展名。
猜你喜欢
  • 2014-06-29
  • 2019-01-16
  • 2013-09-02
  • 1970-01-01
  • 2014-04-18
  • 2023-04-09
  • 2021-03-21
  • 2017-10-04
  • 2022-12-18
相关资源
最近更新 更多