Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I turn an EJS template into a string?

I want to pass my variables into that template, let it render, and then get the resulting HTML as a string.

How can I do that in Express?

like image 537
TIMEX Avatar asked Jul 06 '11 00:07

TIMEX


Video Answer


2 Answers

You don't need to use fs. This is built into EJS (not sure if it was at the time previous answer was posted).

It returns a Promise however so you could use Async/await to get the value:

let html
async function myFunc() {
    html = await ejs.renderFile(filePath, data, options)
} 
console.log(html)

Alternatively it provides a callback function:

ejs.renderFile(filePath, data, options, function(err, html) {
    console.log(html)
})
like image 153
Swalden Avatar answered Oct 08 '22 16:10

Swalden


Depending on the ejs version the following should work.

var ejs = require('ejs'),
    fs = require('fs'),
    file = fs.readFileSync(__dirname + '/template.ejs', 'ascii'),
    rendered = ejs.render(file, { locals: { items:[1,2,3] } });

console.log(rendered);

You may need to install ejs if it isn't already installed.

cd;npm install ejs
like image 42
Lime Avatar answered Oct 08 '22 17:10

Lime