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

前端 未结 8 1729
臣服心动
臣服心动 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:40

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

提交回复
热议问题