Render ejs file in node.js

谁说我不能喝 提交于 2019-12-17 18:10:13

问题


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:


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



回答2:


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




回答3:


All you have to do is compile the file as a string (with optional local variables), like so:

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



回答4:


There's a synchronous version of this pattern that tightens it up a little more.

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

Note the use of readFileSync(). If you specify the encoding (utf8 here), the function returns a string containing your template.




回答5:


The answer of @ksloan should be the accepted one. It uses the ejs function precisely for this purpose.

Here is an example of how to use with Bluebird:

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

For the sake of completeness here is a promisified version of the currently accepted answer:

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



回答6:


@ksloan's answer is really good. I also had the same use case and did little bit of digging. The function renderFile() is overloaded. The one you will need mostly is:

renderFile(path: string,data, cb)

for example:

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

where dataForTemplate is an object containing values that you need inside the template.



来源:https://stackoverflow.com/questions/8660659/render-ejs-file-in-node-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!