javascript – 渲染EJS模板并将其另存为文件
作者:互联网
我一直在讨论这个,我试图渲染一个EJS文件并将结果保存为HTML,保存部分似乎正在工作,但我无法全面了解如何从’返回数据模板’文件.
var fileName = 'public/cv/' + userID + '_default.html';
var stream = fs.createWriteStream(fileName);
function buildHtml(request) {
var sveducations = JSON.parse(SQReducations);
var header = '';
return '<!DOCTYPE html>'
+ '<html><header>' + header + '</header><body>' +
html
+
'</body></html>';
};
stream.once('open', function (fd) {
var html = buildHtml();
stream.end(html);
});
解决方法:
这是保存从ejs呈现的html字符串的最简单方法.
var ejs = require('ejs');
var fs = require('fs');
var data = {} // put your data here.
var template = fs.readFileSync('./template.ejs', 'utf-8');
var html = ejs.render ( template , data );
fs.writeFileSync("./html.html", html, 'utf8');
如果要从JSON文件中读取数据
var data = JSON.parse(fs.readFileSync('./data.json', 'utf8'));
8/12编辑
使用try catch获取错误消息.
var ejs = require('ejs');
var fs = require('fs');
var data = {} // put your data here.
try {
var template = fs.readFileSync('./template.ejs', 'utf-8');
var html = ejs.render ( template , data );
fs.writeFileSync("./result.html", html, 'utf8');
}catch (e){
console.log(e) // If any error is thrown, you can see the message.
}
标签:templating,javascript,node-js,ejs 来源: https://codeday.me/bug/20190828/1756735.html