2012-08-23 118 views
5

我正在使用node.jsJade模板系統。node.js中Jade模板的全局變量

假設,我有這些路由規則:

// ./routes/first.js 

exports.first = function(req, res) 
{ 
    res.render('first', { 
     author: 'Edward', 
     title: 'First page' 
    }); 
}; 

// ./routes/second.js 

exports.second = function(req, res) 
{ 
    res.render('second', { 
     author: 'Edward', 
     title: 'Second page' 
    }); 
}; 

而且這些虛擬的觀點:

// ./views/first.jade 

html 
    head 
     title #{author} – #{title} 
    body 
     span First page content 

// ./views/second.jade 

html 
    head 
     title #{author} – #{title} 
    body 
     span Second page content 

我怎樣才能申報一般author變量,這兩種觀點?

+0

重複http://stackoverflow.com/questions/4718818/express-js-view-globals的 –

回答

2
// ./author.js 
module.exports = 'Edward'; 

// ./routes/first.js 

exports.first = function(req, res) 
{ 
    res.render('first', { 
     author: require('../author'), 
     title: 'First page' 
    }); 
}; 

// ./routes/second.js 

exports.second = function(req, res) 
{ 
    res.render('second', { 
     author: require('../author'), 
     title: 'Second page' 
    }); 
}; 

// ./views/includes/head.jade 
head 
    title Edward – #{title} 

// ./views/first.jade 

html 
    include includes/head 
    body 
     span First page content 

// ./views/second.jade 

html 
    include includes/head 
    body 
     span Second page content 

// ./views/layout.jade 
html 
    head 
     title Edward – #{title} 
    body 
     block body 

// ./views/first.jade 

extends layout 
append body 
    span First page content 

// ./views/second.jade 

extends layout 
append body 
    span Second page content 
+0

謝謝您的回答,我一直在使用繼承的模板,就像你在第二個變體中提出的一樣。只是想知道,如果有可能使它更容易。還沒找到更好的東西。 :)第一個例子很複雜。 –

+0

使用'app.locals.author =「Jeffry」'來代替,因此您不必在任何地方重複您的代碼(DRY - https://en.wikipedia.org/wiki/Don't_repeat_yourself) –

+0

@JanJůna,請勿使用全局狀態,因此您可以輕鬆測試和支持您的代碼(https://en.wikipedia.org/wiki/Global_variable#Use) – penartur