简体   繁体   English

如何将 EJS 模板转换为字符串?

[英]How can I turn an EJS template into a string?

I want to pass my variables into that template, let it render, and then get the resulting HTML as a string.我想将我的变量传递到该模板中,让它渲染,然后将生成的 HTML 作为字符串获取。

How can I do that in Express?我怎样才能在 Express 中做到这一点?

Depending on the ejs version the following should work.根据 ejs 版本,以下应该可以工作。

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.如果尚未安装 ejs,您可能需要安装它。

cd;npm install ejs

You don't need to use fs.你不需要使用 fs。 This is built into EJS (not sure if it was at the time previous answer was posted).这是内置在 EJS 中的(不确定它是否是在发布之前的答案时)。

It returns a Promise however so you could use Async/await to get the value:它返回一个 Promise 但是你可以使用 Async/await 来获取值:

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

Alternatively it provides a callback function:或者,它提供了一个回调 function:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM