问题
This seems to me like a pretty basic question, but I haven't been able to find an answer.
I'm using express with ejs
as template engine and the following dir structure:
|-static
|---css
|---img
|---js
|-views
I have static routing defined for static
folder:
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.bodyParser());
app.use(partials());
app.use(express.methodOverride());
app.use(express.static(__dirname + '/static'));
app.use(app.router);
app.enable("jsonp callback");
});
In Views
folder i keep all of my ejs
files - one layout.ejs
and the rest are files with the actual content of the specific page.
I've defined the following routes:
app.get('/', function(req,res){
locals.date = new Date().toLocaleDateString();
res.render('home.ejs', locals);
});
app.get('/about', function(req,res){
locals.date = new Date().toLocaleDateString();
res.render('about.ejs', locals);
});
app.get('/contact', function(req,res){
locals.date = new Date().toLocaleDateString();
res.render('contact.ejs', locals);
});
which takes layout.ejs
and renders it with the page together.
Obviously I don't want to add a new route each time I add a new page, I want it to be done automatically.
So I am guessing it should have to do with defining another app.use(express.static(__dirname + '/views'));
? also I don't want the url to show /about.ejs
but to show /about
Can someone please point me in the right direction ?
Thanks !
回答1:
You can write your own routing logic, for example
function customRouter (req, res, next)
{
var locals = {};
var controllerName = req.params.controllerName;
res.render(controllerName + '.ejs', locals);
}
app.get('/:controllerName', customRouter);
This is a simple example however it should give you the trick. You can modify it according to your own needs.
来源:https://stackoverflow.com/questions/13430561/node-js-and-express-static-middleware-routing-views