2012-12-13 34 views
1

我想用jade渲染一個頁面。在我的路線文件我有這樣的:爲什麼我的玉變量未定義?

exports.start = function(req, res){ 
    res.render('start', { 
     title: 'Special you!', 
     locals: { 
      percent: 0 
     } 
    }); 
}; 

在start.jade文件我想用這樣的百分比變量:

.progress.progress-success 
    .bar(style='width: #{locals.percent}') 

我也包含在本start.jade代碼,調試的目的:

each item in locals 
    p= item 

輸出是這樣的:

[object Object] 

Special you! 

function locals(obj){ for (var key in obj) locals[key] = obj[key]; return obj; } 

false 

C:\Users\Alexandru\Documents\GitHub\yolo-adventure\views\start.jade 

並且locals.percent的值未定義。

完整start.jade文件是:

extends layout 

block custom-style 
    link(rel='stylesheet', href='/stylesheets/main-style.css') 

block content 
    h1 Start from here 
    each item in locals 
     p= item 

    .progress.progress-success 
     .bar(style='width: #{locals.percent}') 

頁面的源代碼是這樣的:

<!DOCTYPE html> 
<html> 
    <head> 
     <title>Special you!</title> 
     <link rel="stylesheet" href="/stylesheets/bootstrap.css"> 
     <link rel="shortcut icon" href="/images/favicon.png"> 
     <link rel="stylesheet" href="/stylesheets/main-style.css"> 
    </head> 
    <body> 
     <h1>Start from here</h1> 
     <p>[object Object]</p> 
     <p>Special you!</p> 
     <p>function locals(obj){ 
       for (var key in obj) locals[key] = obj[key]; 
        return obj; 
      } 
     </p> 
     <p>false</p> 
     <p>C:\Users\Alexandru\Documents\GitHub\yolo-adventure\views\start.jade</p> 
     <div class="progress progress-success"> 
      <div style="width: undefined" class="bar"></div> 
     </div> 
    </body> 
</html> 

這究竟是爲什麼?

+0

它說「undefined」? '特別你!'從哪裏來? – Amberlamps

+0

哦..我將標題值從Special改爲!到你好,當我創建這篇文章,但在我的代碼是「特別你!」 –

回答

2

服務器端

只要定義當地人直接:

res.render('start', { 
    title: 'Special you!', 
    percent: 0 
}); 

客戶端

然後,你可以這樣做:

.progress.progress-success 
    .bar(style='width: ' + percent + ';') 

另一個鐵道部解決這個問題的一般方法是在Javascript中創建一個變量,然後將HTML屬性設置爲該JavaScript變量。

.progress.progress-success 
    - var bar_style = 'width: ' + percent + ';'; 
    .bar(style=bar_style) 
相關問題