2012-08-23 4 views
5

Sto usando node.js con il sistema di modelli Jade.Variabile globale per i modelli di giada in node.js

Assumere, ho queste regole di routing:

// ./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' 
    }); 
}; 

E questi punti di vista fittizi:

// ./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 

Come posso dichiarare author variabile in genere, sia per i punti di vista?

+0

duplicati di http://stackoverflow.com/questions/4718818/express-js-view-globals –

risposta

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' 
    }); 
}; 

o

// ./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 

o

// ./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

Grazie per la risposta, ho Ho usato modelli ereditati, come proponendo nella seconda variante. Mi chiedevo solo se è possibile renderlo più facile. Non ho ancora trovato nulla di meglio. :) Il primo esempio è solo complicato. –

+0

Usa 'app.locals.author =" Jeffry "' invece non devi ripetere il codice ovunque (DRY - https://en.wikipedia.org/wiki/Don't_repeat_yourself) –

+0

@ JanJůna, non usare stato globale in modo da poter testare e supportare facilmente il tuo codice (https://en.wikipedia.org/wiki/Global_variable#Use) – penartur