2012-08-23 6 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

おかげで、I第2の変種で提案しているように、継承されたテンプレートを使用しています。ちょっとだけ思っていました。まだ何も見つけていない。 :)最初の例はちょうど複雑です。 –

+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

関連する問題