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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With