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

前端 未结 8 1706
臣服心动
臣服心动 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 06:05

    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.

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

    Use ejs.renderFile(filename, data) function with async-await.

    To render HTML files.

    const renderHtmlFile = async () => {
        try {
            //Parameters inside the HTML file
            let params = {firstName : 'John', lastName: 'Doe'};
            let html = await ejs.renderFile(__dirname + '/template.html', params);
            console.log(html);
        } catch (error) {
            console.log("Error occured: ", error);
        }
    }
    

    To render EJS files.

    const renderEjsFile = async () => {
        try {
            //Parameters inside the HTML file
            let params = {firstName : 'John', lastName: 'Doe'};
            let ejs = await ejs.renderFile(__dirname + '/template.ejs', params);
            console.log(ejs);
        } catch (error) {
            console.log("Error occured: ", error);
        }
    }
    
    0 讨论(0)
提交回复
热议问题