Tin*_*no' 5 javascript templating ejs node.js
我一直在努力解决这个问题,我试图呈现一个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);
});
Run Code Online (Sandbox Code Playgroud)
这是保存从 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');
Run Code Online (Sandbox Code Playgroud)
如果你想从 JSON 文件中读取数据
var data = JSON.parse(fs.readFileSync('./data.json', 'utf8'));
Run Code Online (Sandbox Code Playgroud)
使用 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.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2364 次 |
| 最近记录: |