在node.js中渲染ejs文件

嘿,我正在玩node.js,并试图呈现模板文件。 我想出了如何呈现string:

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

我怎样才能渲染一个模板文件?

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

然后你做你的事情:

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

在ejs中有一个未公开的函数来渲染文件,你可以做…

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

资源

你所要做的就是将文件编译为一个string(带有可选的局部variables),如下所示:

 var fs = require('fs'), ejs = require('ejs'), http = require('http'), server, filePath; filePath = __dirname + '/sample.html'; // this is from your current directory fs.readFile(filePath, 'utf-8', function(error, content) { if (error) { throw error); } // start the server once you have the content of the file http.createServer(function(req, res) { // render the file using some local params res.end(ejs.render(content, { users: [ { name: 'tj' }, { name: 'mape' }, { name: 'guillermo' } ] }); }); }); 

这个模式有一个同步的版本,可以把它拉紧一点。

 var server = http.createServer(function(req, res) { var filePath = __dirname + '/sample.html'; var template = fs.readFileSync(filePath, 'utf8'); res.end(ejs.render(template,{})); }); 

请注意使用readFileSync ()。 如果你指定了编码(这里是utf8),该函数返回一个包含你的模板的string。

@ksloan的答案应该是公认的答案。 它使用ejs函数正是为了这个目的。

这里是一个如何使用蓝鸟的例子:

 var Promise = require('bluebird'); var path = require('path'); var ejs = Promise.promisifyAll(require('ejs')); ejs.renderFileAsync(path.join(__dirname, 'template.ejs'), {context: 'my context'}) .then(function (tpl) { console.log(tpl); }) .catch(function (error) { console.log(error); }); 

为了完整起见,这里是目前接受的答案的一个promised版本:

 var ejs = require('ejs'); var Promise = require('bluebird'); var fs = Promise.promisifyAll(require('fs')); var path = require('path'); fs.readFileAsync(path.join(__dirname, 'template.ejs'), 'utf-8') .then(function (tpl) { console.log(ejs.render(tpl, {context: 'my context'})); }) .catch(function (error) { console.log(error); });