4

What is the purpose of the res.render callback argument?

In which case would one want to use such a callback argument, since a template is already assigned as the first argument?

Here's the code from the documentation:

// send the rendered view to the client
res.render('index');

// if a callback is specified, the rendered HTML string has to be sent explicitly
res.render('index', function(err, html) {
  res.send(html);
});

// pass a local variable to the view
res.render('user', { name: 'Tobi' }, function(err, html) {
  // ...
});

I understand the purpose of the first two arguments, but not the last.

roadtocode
  • 329
  • 5
  • 13

1 Answers1

3

With the callback, you can intercept the rendered template before sending it on. You might want to minify it or otherwise modify it before sending to the client.

From the documentation:

If provided, the method returns both the possible error and rendered string, but does not perform an automated response.

Brad
  • 159,648
  • 54
  • 349
  • 530
  • Thanks. That makes sense that one would want to minify the template before sending it on. Do you have any other cases of modification that may be useful for utilizing this callback argument? – roadtocode Jun 06 '17 at 03:08
  • @roadtocode Depends on what you want to do... you can use it for anything you need. – Brad Jun 06 '17 at 03:09
  • For example, I have used the data part of that render to send HTML-email (body from the HBS rendered). Once the email is sent, I rendered another JSON as API response. BTW, Is there any other way of invoking render without REQ? Ideally, I would like to have this HBS-render in my model-code to get the email content, not in routes, – Satya Kalluri Oct 08 '20 at 11:24