render EJS template and save it as a file
Asked Answered
I

2

7

I have been cracking my head over this, I am trying to render an EJS file and save the result as an HTML, the saving part seems to be working but I can't get the full hand of how to return the data from the 'template' file.

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);
    });
Irrupt answered 11/8, 2016 at 8:9 Comment(1)
first of all <body>' + html + '</body> the html variable seems to not be defined. The what do you mean by how to return the data from the 'template' file ?Pantelleria
S
8

This is the simplest way to save html string rendered from ejs.

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');

If you want to read data from JSON file

var data = JSON.parse(fs.readFileSync('./data.json', 'utf8'));

8/12 edit

Use try catch to get error message.

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.
}
Skolnik answered 11/8, 2016 at 8:21 Comment(2)
I edited my answer,please use try catch to get error information.Skolnik
You can avoid using readFileSync() by using ejs.renderFile() ;) Check my answer bellowNicobarese
N
3

Now you don't need anymore to load the template with a readFile() or readFileSync() call. You can simply use ejs.renderFile(pathToTemplate, data, cal) :

const data = {};

ejs.renderFile(path.join(__dirname, '../views/template.ejs'), data, (err, result) => {
    if (err) {
        logger.log('info', 'error encountered: ' + err);
        // throw err;
    }
    else {
        try {
            fs.writeFileSync('./html.html', result, 'utf8');
        } catch(err) {
            if (err) {
                throw err;
            }
        }

    }
});
Nicobarese answered 17/4, 2017 at 17:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.