Question

I'm having a few issues with Jade and scope of variables exported from the route. This might be an obvious answer, but my googling abilities have failed me.

In my route, I have this code :

res.render('index', {title: "App",
                     csvData: json  // This is a json object
};

In my view, I want to display the length of the json object on the click of a button. My jade looks like this :

extends layout
block content
  script
    -var test123 = csvData;
    -console.log(test123.length);
  div 
    button.btnCSV(onclick='console.log(test123)') Save As CSV

The first console.log prints the correct length, but when I do press the button, it tells me that test123 is undefined. I think this has something to do with the difference between client side/server side variables. If that is the case, is there anyway to make a server side variable accessible to a client side scope?

Was it helpful?

Solution

I'm not sure how your example would work with the script content prefixed with a -, this indicates unbuffered code. JavaScript that runs server side and that produces no direct output, so your in-line script is most likely empty.

Similarly your onclick handler is just compiling a string on the server, which is the main problem you appear to report.

In order to achieve what you trying to do, you should define a function in the script block which can be called from your buttons onclick handler. Take care to ensure that your script keyword ends with a . so that the following lines are treated as block content of the script.

Here's what your template should look like.

extends layout
block content
  script.
    var test123 = !{JSON.stringify(csvData)};
    function printLength() { 
      console.log(test123.length);
    }
  div 
    button.btnCSV(onclick='printLength()') Save As CSV

Then on the server side make sure you're returning an actual JavaScript object, or an Array, and not a string representation... it should look like this

res.render('index', {title: "App",
                     csvData: [{ val1: 'value1', val2: 'value2' }]  
};

This allows variables to be used for server side scripting (if required) as well as client side.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top