Node.js和Express静态中间件路由视图 [英] Node.js and Express static middleware routing views
问题描述
在我看来,这是一个非常基本的问题,但我找不到答案。
This seems to me like a pretty basic question, but I haven't been able to find an answer.
我正在将Express与<$ c $一起使用c> ejs 作为模板引擎和以下目录结构:
I'm using express with ejs
as template engine and the following dir structure:
|-static
|---css
|---img
|---js
|-views
我为 static
文件夹定义了静态路由:
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");
});
在 Views
文件夹中,我保留了所有 ejs
文件-一个 layout.ejs
文件,其余的是具有特定页面实际内容的文件。
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.
我定义了以下路线:
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);
});
接受 layout.ejs
并将其渲染
显然,我不想每次添加新页面时都添加新路线,而是希望它自动完成。
Obviously I don't want to add a new route each time I add a new page, I want it to be done automatically.
所以我想这应该与定义另一个 app.use(express.static(__ dirname +'/ views'));
?我也不希望该URL显示 /about.ejs
,而是显示 / about
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 ?
谢谢!
推荐答案
您可以编写自己的路由逻辑,例如
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.
这篇关于Node.js和Express静态中间件路由视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!