2012-08-23 41 views
5

Tôi đang sử dụng node.js với hệ thống templating Jade.Biến toàn cục cho các mẫu Jade trong node.js

Giả sử, tôi có những quy tắc định tuyến:

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

Và những quan điểm giả:

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

Làm thế nào tôi có thể tuyên bố author biến nói chung, đối với cả hai quan điểm?

+0

Duplicate của http://stackoverflow.com/questions/4718818/express-js-view-globals –

Trả lời

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

hoặc

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

hoặc

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

Cám ơn câu trả lời của bạn, tôi đã sử dụng các mẫu được kế thừa, như bạn đề xuất trong biến thể thứ hai. Chỉ cần tự hỏi, nếu nó có thể làm cho nó dễ dàng hơn. Chưa tìm thấy gì tốt hơn. :) Ví dụ đầu tiên chỉ phức tạp. –

+0

Sử dụng 'app.locals.author =" Jeffry "' thay vào đó để bạn không phải lặp lại mã của mình ở mọi nơi (DRY - https://en.wikipedia.org/wiki/Don't_repeat_yourself) –

+0

@ JanJůna, không sử dụng trạng thái toàn cầu để bạn có thể kiểm tra và hỗ trợ mã của mình một cách dễ dàng (https://en.wikipedia.org/wiki/Global_variable#Use) – penartur

Các vấn đề liên quan