使用node / express包含页眉/页脚的更好方法?
在我们使用fs.write而不是fs.render并希望在输出中包含页眉和页脚的情况下。我尝试使用include,它给出了一个错误。
这样的行不起作用 - > const head = require('../ views / partials / production-header.html');
async function readInFile(theFile) {
return await fs.readFile(path + theFile)
}
router.get('/:qry', function(req, res) {
readInFile('/views/partials/production-header.html').then(data => {
let head = data.toString()
readInFile('/views/partials/production-footer.html').then(data => {
let foot = data.toString()
display_page(head, foot)
})
})
})
function display_page(head,foot,filter) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(head);
res.write(q);
res.write(foot);
res.end();
}
上述工作,但似乎不是最好的方式去做
回答如下:有很多模板引擎,并且非常容易使用,例如pug,你可以找到快速here的集成教程