How can I turn an EJS template into a string?

こ雲淡風輕ζ 提交于 2019-12-09 15:40:02

问题


I want to pass my variables into that template, let it render, and then get the resulting HTML as a string.

How can I do that in Express?


回答1:


Depending on the ejs version the following should work.

var ejs = require('ejs'),
    fs = require('fs'),
    file = fs.readFileSync(__dirname + '/template.ejs', 'ascii'),
    rendered = ejs.render(file, { locals: { items:[1,2,3] } });

console.log(rendered);

You may need to install ejs if it isn't already installed.

cd;npm install ejs



回答2:


You don't need to use fs. This is built into EJS (not sure if it was at the time previous answer was posted).

It returns a Promise however so you could use Async/await to get the value:

let html
async function myFunc() {
    html = await ejs.renderFile(filePath, data, options)
} 
console.log(html)

Alternatively it provides a callback function:

ejs.renderFile(filePath, data, options, function(err, html) {
    console.log(html)
})


来源:https://stackoverflow.com/questions/6590333/how-can-i-turn-an-ejs-template-into-a-string

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