对于仍在尝试弄清楚如何实现异步 ejs 模板的人,我在下面列出了我的完整解决方案:
在您的主应用文件 (app.js) 中
// app.js
// Set ejs as view engine
app.set('view engine', 'ejs');
let ejsOptions = {
// delimiter: '?', Adding this to tell you do NOT use this like I've seen in other docs, does not work for Express 4
async: true
};
// The engine is using a callback method for async rendering
app.engine('ejs', async (path, data, cb) => {
try{
let html = await ejs.renderFile(path, data, ejsOptions);
cb(null, html);
}catch (e){
cb(e, '');
}
});
现在您的路线响应...
app.route('/login')
.get( async (req, res) =>{
// layout.ejs is my version of blocking. I pass the page name as an option to render custom pages in the template
return await res.render(`layout.ejs`, { page : 'login' }, (err, html) => standardResponse(err, html, res));
})
我在回调中使用函数 standardResponse() 以提高可读性,因此我必须编写更少的行。函数是这样工作的……
const standardResponse = (err, html, res) => {
// If error, return 500 page
if (err) {
console.log(err);
// Passing null to the error response to avoid infinite loops XP
return res.status(500).render(`layout.ejs`, { page : '500', error: err }, (err, html) => standardResponse(null, html, res));
// Otherwise return the html
} else {
return res.status(200).send(html);
}
}
还有中提琴!异步ejs渲染。