Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express, check if a template exists

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.

like image 686
edA-qa mort-ora-y Avatar asked Jun 07 '13 12:06

edA-qa mort-ora-y


1 Answers

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.

like image 110
robertklep Avatar answered Nov 12 '22 16:11

robertklep