如何在不执行 `res.render` 的情况下在 nodeJS/express 中使用 EJS 模板引擎?

How can I use the EJS templating engine in nodeJS/express without doing `res.render`?

我想要 res.send 一个 JSON 对象,其中包含从我的一个 EJS 模板生成的 HTML 片段。

res.send({
    status: "xyz",
    timestamp: new Date(),
    htmlContent: "" //=====> HTML snippet from template.ejs here
});

这有可能吗?谢谢!

简短回答:是的,但我不推荐它。

长答案:是的,尽管您需要自己使用 ejs 模板库:

var ejs = require('ejs');
var template = ejs.compile('<h1>Template</h1><p><%= data %></p>'), options);
var renderedTemplate = template({data: 'My Data'});
//renderedTemplate would contain '<h1>Template</h1><p>My Data</p>'

这会给你想要的。但老实说,这与仅使用 res.render 并没有太大区别。是的,express 必须读取视图文件,但这可以通过缓存模板(它确实如此)来缓解。您的模板最好在您的请求处理程序代码之外,恕我直言。

您可以 "render" 将 ejs 内容添加到变量并将其添加到对象。

var content='';
res.render('template', function(err, html) {
   content = html;
});
res.send({
    status: "xyz",
    timestamp: new Date(),
    htmlContent: content
});

如果这就是您想要做的,那么我们可以缩短代码:

res.render('template', function(err, html) {
   res.send({
     status: "xyz",
     timestamp: new Date(),
     htmlContent: html
   });
});