How do I render an EJS template file in Node.js?

前端 未结 8 1757
臣服心动
臣服心动 2020-12-05 05:24

I\'m using Node.js and trying to render an EJS template file. I figured out how to render strings:

    var http = requ         


        
8条回答
  •  不知归路
    2020-12-05 05:43

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

提交回复
热议问题