Chris Ebert Chris Ebert - 5 months ago 11
Node.js Question

Load different EJS, depending on URL

If the URL contains 'todos', for example, '.../todos/*', he should load a different EJS template (todos.ejs). If the URL doesn’t contain 'todos', the normal index.ejs will load.

I tried something like below, but I think the use of

app.get
is wrong.

if (req.url.indexOf("todos") >= 0) {
app.get('/todos/*', function(req, res) {
res.render('todos', {
title: 'todos page'
});
});
} else {
app.get('/', function(req, res) {
res.render('index', {
title: 'index page'
});
});
}

Answer

You can use regular expressions to match URL paths with Express, so:

// Match any URL with '/todos/' in the path:
app.get(/\/todos\//, function(req, res) {
  res.render('todos', { title: 'todos page' });
});

// Match the rest:
app.get('*', function(req, res) {
  res.render('index', { title: 'index page' });
});

If you don't care about the slashes surrounding "todos", the match becomes this:

app.get(/todos/, ...);

Note that the order of declaring route handlers matters: you want to declare the most specific match (the "todos" one) first, least specific ("the rest") last.