关于javascript:在Express中使用res.json时,替代fs.readFile加载Handlebars模板

Alternative to fs.readFile to load Handlebars template when using res.json in Express

我的目标是在我正在构建的Express 4应用程序中提供一个简单的实时api端点(使用res.json()),该应用程序将Handlebars模板与数据一起编译,并返回一个字符串,该字符串随后将替换HTML客户端。

我遇到的问题是,当我希望使用与显示一般视图相同的机制时,当前必须使用fs.readFile()来读取模板的Handlebars内容。这有可能吗?

这是一个基本示例;

数据终结点(json):

1
2
3
{
 "title":"Page Title"
}

template.hbs

1
{{ title }}

活动端点(json)

1
2
3
{
 "tpl":"Page Title
}

我的路线响应中的功能

1
2
3
4
5
6
7
8
9
10
11
12
var api = {};

fs.readFile('template.hbs', 'utf8', function(err, tpl) {

  var template = hbs.compile(tpl);

  // data here is the value returned from the data endpoint above
  api.tpl = template(data);

  res.json(api);

});

我什至不需要担心,因为这也许是Handlebars在幕后所做的一切,但我只是想知道是否有一种我不知道的简单方法。


我建议您使用express-handlebars将把手用作渲染引擎。只需执行以下操作:

1
2
3
4
5
6
const expressHandlebars = require('express-handlebars');

...

app.engine('handlebars', expressHandlebars({/* config */}));
app.set('view engine', 'handlebars');

现在,假设您已为应用程序传递了正确的配置选项,您的模板将使用车把进行渲染。现在您可以使用普通的Express API,如下所示:

1
2
3
4
5
6
...

res.render('template', data, (err, html) => {
  api.tpl = html;
  res.json(api);
});