且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Express - 异步模板

更新时间:2023-10-25 22:14:22

Handlebars不是一个异步模板引擎,因此不可能。您需要切换到Node.js的异步模板引擎,例如 Marko 。即使在渲染开始后,Marko也允许您异步获取更多数据。


I'm using Express-Handlebars for my templating engine and I'd like to make an asynchronous call from within my templates like the following example:

{{{cmsLoader 'search-{$searchTerm}' searchTerm=query.input defaultId='search-default'}}}

This would query the db for a chunk of html by a specific id (i.e. 'search-video-games'), if the key exists, it adds the html. If the key doesn't exist, it looks for the defaultId (i.e. 'search-default') and adds it instead. If the defaultId is not specified or doesn't exist, nothing is added.

Most of the backend functionality is in place. My problem is the doing async processing inside of a helper. Is there a way to wait for the results of an async call from an hbs-helper before finalizing the render?

NOTE:

I realize I can make these calls from inside the controller and feed the data to the view, but there are tons of templates most with multiple CMS blocks and since these will be changing regularly, accounting for them ahead of time would be difficult to maintain.

Handlebars is not an asynchronous templating engine so that is not possible. You would need to switch to an asynchronous templating engine for Node.js such as Marko. Marko allows you to asynchronously fetch additional data even after rendering has begun.