1

我想执行 res.render,但不是像这样将模板文件作为参数传递:

res.render('index.hbs', { a: 'B' });

我希望能够将模板作为这样的字符串传递:

let template = '{{ a }}'
res.render(template, { a: 'B' });

上面的代码显然不起作用,因为 res.render 只接受文件路径/名称。关于如何实现这一目标的任何想法?

4

1 回答 1

2

你可以先渲染你的模板

var handlebars = require('handlebars');

// set up your handlebars template
var source = '{{ a }}';

// compile the template
var template = handlebars.compile(source);

// call template as a function, passing in your data as the context
var outputString = template({ a: 'B' });

然后将输出发送给客户端

res.send(outputString);
于 2017-08-18T08:06:49.823 回答