加载不同的 EJS,取决于 URL
Load different EJS, depending on URL
如果URL包含'todos',例如'.../todos/*',他应该加载不同的EJS模板(todos.ejs)。如果 URL 不包含 'todos',将加载正常的 index.ejs。
我尝试了类似下面的方法,但我认为 app.get
的使用是错误的。
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'
});
});
}
应该是这样的。
app.get('*', function(req, res) {
if (req.url.indexOf("todos") >= 0) {
return res.render('todos', {
title: 'todos page'
});
}
res.render('todos', {
title: 'todos page'
});
});
试试这个
app.get('*', (req, res) => {
if (req.url.indexOf('todos') === -1) {
return res.render('index', { title: 'index page'})
}
else {
return res.render('todos', { title: 'todos page' })
}
})
您可以在 Express 中使用 regular expressions to match URL paths,因此:
// 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' });
});
如果您不关心 "todos" 周围的斜线,匹配将变成这样:
app.get(/todos/, ...);
请注意声明路由处理程序的顺序很重要:您要首先声明最具体的匹配项("todos"),最不具体的 ("the rest") 最后。
如果URL包含'todos',例如'.../todos/*',他应该加载不同的EJS模板(todos.ejs)。如果 URL 不包含 'todos',将加载正常的 index.ejs。
我尝试了类似下面的方法,但我认为 app.get
的使用是错误的。
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'
});
});
}
应该是这样的。
app.get('*', function(req, res) {
if (req.url.indexOf("todos") >= 0) {
return res.render('todos', {
title: 'todos page'
});
}
res.render('todos', {
title: 'todos page'
});
});
试试这个
app.get('*', (req, res) => {
if (req.url.indexOf('todos') === -1) {
return res.render('index', { title: 'index page'})
}
else {
return res.render('todos', { title: 'todos page' })
}
})
您可以在 Express 中使用 regular expressions to match URL paths,因此:
// 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' });
});
如果您不关心 "todos" 周围的斜线,匹配将变成这样:
app.get(/todos/, ...);
请注意声明路由处理程序的顺序很重要:您要首先声明最具体的匹配项("todos"),最不具体的 ("the rest") 最后。