ExpressJS View 中共用/分享/全域變數


在 app.js 的設定中設置 view options 這個值的內容,如:

1
2
3
4
5
app.configure(function(){
app.set('view options', {
siteTitle: config.siteTitle
})
});

而原來的頁面代碼就會長得像這樣:

1
2
3
app.get('/', function(req, res) {
res.render('index/index');
});

之後就可以直接在模版中使用 siteTitle 這變數

1
2
3
4
!!!
html
head
title= siteTitle

除了設置 view options 的內容外,
也可以通過注冊 helper 這類方法實現

1
2
3
app.helpers({
config: config
});
1
2
3
4
!!!
html
head
title= config.site_name