Render ejs file in node.js


Question

Hey guys I'm playing with node.js and trying to render an template file. I figured out how to render strings:

var http = require('http');
var ejs = require('ejs');

var server = http.createServer(function(req, res){
    res.end(ejs.render('Hello World'));
});

server.listen(3000);

How can I render a template file?

1
17
12/28/2011 8:01:54 PM

Accepted Answer

var templateString = null;
var fs = require('fs');
var templateString = fs.readFileSync('template.ejs', 'utf-8');

and then you do your thing:

var server = http.createServer(function(req, res){
    res.end(ejs.render(templateString));
});
23
9/14/2015 11:04:14 AM

There is an undocumented function in ejs to render files, you can just do...

ejs.renderFile(__dirname + '/template.ejs', function(err, data) {
    console.log(err || data)
})

source


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon