为什么我的玉变量未定义?

时间:2012-12-13 11:01:00

标签: node.js variables undefined pug

我想使用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>

为什么会这样?

1 个答案:

答案 0 :(得分: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)