【问题标题】:nodejs handlebars: 'TypeError: this.engine is not a function'nodejs车把:'TypeError:this.engine不是函数'
【发布时间】:2023-04-09 19:45:01
【问题描述】:

我尝试在 Express 中使用车把模板。我收到此错误消息:

TypeError: this.engine 不是一个函数 在 View.render (/home/ubuntu/workspace/node_modules/express/lib/view.js:128:8) ...

使用此代码:

'use strict';

var express = require('express');
var expressHandlebars  = require('express-handlebars');

var app = express();

app.engine('handlebars', expressHandlebars({defaultLayout: 'layout'}));
app.set('view engine', 'html');
app.use(express.static('views'));

app.route('/single/:id')
    .get(function (req, res) {
        res.render(process.cwd() + `/public/single-poll`, {
            id: req.params.id
        });
    });

app.listen(process.env.PORT,  function () {
    console.log('Node.js listening on port ' + process.env.PORT + '...');
});

当我用 sendFile() 替换 render() 函数时工作正常。我知道Express js render : TypeError: this.engine is not a functionExpress js render error this.engine is not a functionTypeError: this.engine is not a function when trying to use Moustache in Express JS,但它们对我没有帮助。

可能是什么问题?

【问题讨论】:

    标签: node.js express handlebars.js render


    【解决方案1】:

    感谢@Patrick Roberts 关于阅读手册的评论,我重写了它,这就是它的工作原理:

    'use strict';
    
    var express = require('express');
    var exphbs  = require('express-handlebars');
    
    var app = express();
    
    app.engine('handlebars', exphbs({defaultLayout: 'main'}));
    app.set('view engine', 'handlebars');
    
    app.route('/single/:id')
        .get(function (req, res) {
            res.render('single-poll', {
                id: req.params.id
            });
        });
    
    app.listen(process.env.PORT,  function () {
        console.log('Node.js listening on port ' + process.env.PORT + '...');
    });
    

    我认为主要是将文件结构更改为:

    ├── app.js
        └── views
            ├── single-poll.handlebars
            └── layouts
                └── main.handlebars
    

    【讨论】:

      【解决方案2】:

      由于您的车把模板文件保存为.html,您应该将引擎注册为'html',而不是'handlebars'

      app.engine('html', expressHandlebars({defaultLayout: 'layout', extname: '.html', layoutsDir: 'public/'}));
      app.set('view engine', 'html');
      app.set('views', 'public/');
      
      // ...
      res.render('single-poll', ...);
      

      你的项目目录应该是这样的(我希望):

      ├── app.js
      └── public
          ├── layout.html
          └── single-poll.html
      

      在找到您需要更改的所有内容后,我真的建议您坐下来并read the ******* manual,因为我建议的所有内容都在那里。

      【讨论】:

      • 尝试从您的res.render() 呼叫中删除文件扩展名。这样能解决吗?
      • 不,它没有。
      猜你喜欢
      • 2016-12-06
      • 1970-01-01
      • 2022-01-18
      • 2015-12-13
      • 2017-09-26
      • 1970-01-01
      • 1970-01-01
      • 2013-11-17
      • 2016-03-02
      相关资源
      最近更新 更多