Express.js自定义模板引擎(板)
我正在尝试让板模板引擎与express.js 一起使用。我最初的尝试是这样的:
app.register('.html', {
compile: function (str, options) {
var template = new plate.Template(str);
return function(locals) {
return template.render(locals, function(err, data) {
return data;
});
}
}
});
我发现问题是 template.render 不返回任何内容(未定义),而是将数据传递给回调。我不确定如何使其在这种情况下工作,因为 Express 期望编译函数返回一个在调用时直接返回渲染模板的函数。
我在想也许我可以使用承诺来解决这个问题,但也没有成功,因为快速代码不期望返回承诺。我不太了解承诺,所以我可能只是做错了:
app.register('.html', {
compile: function (str, options) {
var promise = new Promise();
var template = new plate.Template(str);
return function(locals) {
template.render(locals, function(err, data) {
promise.resolve(data);
});
return promise;
}
}
});
这是一个有效的自定义实现的示例。不同之处在于下划线模板 template() 函数直接返回渲染的字符串,如下所示:
app.register('.html', {
compile: function (str, options) {
var template = _.template(str);
return function (locals) {
return template(locals);
};
}
});
我真的很想使用 Plate 模板,因为 {% block %} 标签太棒了。任何帮助表示赞赏。
相关文档:
I am trying to get plate template engine to work with express.js. My initial attempt was this:
app.register('.html', {
compile: function (str, options) {
var template = new plate.Template(str);
return function(locals) {
return template.render(locals, function(err, data) {
return data;
});
}
}
});
I see that the problem is that template.render doesn't return anything (undefined) but passes the data to a callback. I'm not sure how to make it work in this case as Express expects the compile function to return a function that directly returns a rendered template when called.
I was thinking perhaps I can use promises to solve this issue but had no success there either since the express code doesn't expect a promise to be returned. Im not too up to speed on promises so I may just be doing it wrong:
app.register('.html', {
compile: function (str, options) {
var promise = new Promise();
var template = new plate.Template(str);
return function(locals) {
template.render(locals, function(err, data) {
promise.resolve(data);
});
return promise;
}
}
});
Here is an example of a custom implementation that does works. The difference is that underscore templates template() function directly returns the rendered string like so:
app.register('.html', {
compile: function (str, options) {
var template = _.template(str);
return function (locals) {
return template(locals);
};
}
});
I'd really like to use Plate templates since the {% block %} tag is so awesome. Any help is appreciated.
pertinent documentation:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在我询问后,plate的创建者立即向项目添加了补丁以使其与express兼容。 [email protected]+ 已进行更改,您可以查看实施详细信息此处
The creator of plate promptly added a patch to the project to make it compatible with express after I asked this. [email protected]+ has the change and you can see implementation details here