为什么我的玉variables未定义?
我想用玉来渲染一个页面。 在我的路线文件,我有这个:
exports.start = function(req, res){ res.render('start', { title: 'Special you!', locals: { percent: 0 } }); };
在start.jade文件中,我想使用百分比variables,如下所示:
.progress.progress-success .bar(style='width: #{locals.percent}')
我还在start.jade中包含了这个代码,用于debugging目的:
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>
为什么发生这种情况?
服务器端
直接定义当地人:
res.render('start', { title: 'Special you!', percent: 0 });
客户端
那么你可以这样做:
.progress.progress-success .bar(style='width: ' + percent + ';')
解决这个问题的另一种更一般的方法是在Javascript中创build一个variables,然后将HTML属性设置为该JavaScriptvariables。
.progress.progress-success - var bar_style = 'width: ' + percent + ';'; .bar(style=bar_style)