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

前端 未结 8 1676
臣服心动
臣服心动 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' }
          ]
        });  
      });
    });
    
    0 讨论(0)
  • 2020-12-05 05:42

    There is a function in EJS to render files, you can just do:

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

    Source: Official EJS documentation

    0 讨论(0)
  • 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);
      });
    
    0 讨论(0)
  • 2020-12-05 05:50

    @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.

    0 讨论(0)
  • 2020-12-05 05:55

    Simply set express view engine to "ejs"

    const express = require("express");
    const app = express();
    
    // template engine config
    app.set("view engine", "ejs");
    app.set("views", "views"); // setting the folder that has our views & it is default value even if not declared
    
    app.get("/", (req, res, next) => {
      res.render("index");
    });
    

    and of course you need to set your directory as so:

    • views (contains all main & partial views).
    • app.js (has the above configurations).

    And that is it.

    0 讨论(0)
  • 2020-12-05 05:58
    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));
    });
    
    0 讨论(0)
提交回复
热议问题