5

Is there a way I can tell if a given template exists in express? Basically I want to create specific and fallback templates but don't want to contain that logic in the template itself.

if( res.templateExists( 'specific_page' ) ) {
  res.render( 'specific_page' );
} else {
  res.render( 'generic_page' );
}

The specific_page name is generatead at runtime based on the users device, language, etc.

NOTE: I don't need to know how to do string localization within a template, that I already have. I'm looking for cases where the entire layout/template changes.

edA-qa mort-ora-y
  • 30,295
  • 39
  • 137
  • 267
  • Possible duplicate of [How can I catch a rendering error / missing template in node.js using express.js?](http://stackoverflow.com/questions/7283896/how-can-i-catch-a-rendering-error-missing-template-in-node-js-using-express-js) – Wtower Jan 10 '16 at 18:30

1 Answers1

11

You could use this:

res.render('specific_page', function(err, html) {
  if (err) {
    if (err.message.indexOf('Failed to lookup view') !== -1) {
      return res.render('generic_page');
    }
    throw err;
  }
  res.send(html);
});

This will distinguish between an error thrown because the template couldn't be found (in which case it will render generic_page instead), and any other errors that might occur (which are re-thrown). It's not entirely stable because it relies on the error message that's being thrown, but I don't think there's any other way of determining the type of error.

robertklep
  • 198,204
  • 35
  • 394
  • 381
  • This unfortunately doesn't let me distinguish between an error in the template and the template not existing. Thus I'd be uncertain if I should raise an alarm, fail a test, or otherwise. – edA-qa mort-ora-y Jun 07 '13 at 13:46
  • I see that `err.message` is `template not found: ` with nunjucks 3.0.0. Perhaps it got changed later from `Failed to lookup view` to this. – trss Nov 01 '17 at 11:21
  • @trss given that the answer is more than 4 years old, I wouldn't be surprised :D – robertklep Nov 01 '17 at 11:22
  • I'm using this to have a fallback template. It's disconcerting that there isn't a reliable way to achieve this. If there's any other way to have a fallback, do let me know. – trss Nov 01 '17 at 17:30
  • 2
    @trss you could use `fs.exists(app.get('views') + '/your/template', ...)` or something similar – robertklep Nov 01 '17 at 20:12
  • Wonder if nonexistence of the file would be cached by nunjucks and it would hook into fs changes to detect when the file comes into existence. – trss Nov 02 '17 at 05:33
  • @trss no, and no, would be my guess. Template file resolving is done by Express anyway, not the templating engine. – robertklep Nov 02 '17 at 07:26