ericf / express-handlebars

A Handlebars view engine for Express which doesn't suck.
BSD 3-Clause "New" or "Revised" License
2.32k stars 382 forks source link

How can I register async helpers? #168

Open MacgyverMartins opened 8 years ago

MacgyverMartins commented 8 years ago

First of all, sorry for my bad english. I need write a helper that do a query on mongodb. This helper should be async, like de registerAsyncHelper from express-hbs:

hbs.registerAsyncHelper('readFile', function(filename, cb) {
  fs.readFile(path.join(viewsDir, filename), 'utf8', function(err, content) {
    cb(new hbs.SafeString(content));
  });
});

How can I do this with express-handlebars? I try return a promise, but it's not work. I am beginner with node and handlebars, so sorry if this is a stupid question.

dynnamitt commented 8 years ago

:+1:

tndev commented 8 years ago

The "problem" is most likely that Handlebars itself does not support async helper (feature suggestion | Synchronous/Asynchronous Helpers #717), the ability to have an async helper in express-hbs is a hack on top of handlebars.

s-stude commented 1 year ago

For those who still might be interested:

your HTML

{{renderAsync 'some context'}}

your JS

hbs.registerAsyncHelper( 'renderAsync', async function renderAsync( context, helperFn, resolver ) {
          // await doAsyncStuff();
          resolver( `<p> rendered HTML </p>` )
      }
  )