2017-06-22 47 views
1

我嘗試使用Express中的句柄模板。我得到這個錯誤 - 消息:nodejs handlebars:'TypeError:this.engine不是函數'

TypeError: this.engine is not a function at 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渲染()()函數是工作正常。我知道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,但它們對我沒有幫助。

可能是什麼問題?

回答

0

感謝來自@Patrick羅伯茨關於閱讀使用手冊的評論,我重寫了它,這是它如何工作的:

'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 

找到所有你需要改變的東西后,我真的建議你坐下來,因爲我建議的一切都是正確的。

+0

Thx。但錯誤保持不變。 – Michael

+0

嘗試從res'render()調用中刪除文件擴展名。它解決了嗎? –

+0

不,它沒有。 – Michael