Alexandru N. Onea
Alexandru N. Onea

Reputation: 423

Why is my jade variable undefined?

I want to render a page using jade. In my routes file I have this:

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

In start.jade file I want to use the percent variable like this:

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

I also included this code in start.jade, for debug purpose:

each item in locals
    p= item

The output is this:

[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

and the value of locals.percent is undefined.

the complete start.jade file is:

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

the page source is this:

<!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>

Why is this happening?

Upvotes: 1

Views: 1445

Answers (1)

Matt Kneiser
Matt Kneiser

Reputation: 2146

Server-side

Just define locals directly:

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

Client-side

Then you can just do this:

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

Another more general way to approach this problem is to create a variable in Javascript, and then set the HTML attribute to that Javascript variable.

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

Upvotes: 2

Related Questions