1

My index.js file:

res.render('index', {data:{'hello':'world'}});

my jade file:

p #{data}
script(src="/javascripts/app.js")

This prints the value json object.

now on my app.js file console.log(data); gives an error saying data is undefined.

How can I access the data which was passed from my index.js file in my javascript file.

Arvin Gopi
  • 67
  • 1
  • 6
  • possible duplicate of [How to pass variable from jade template file to a script file?](http://stackoverflow.com/questions/8698534/how-to-pass-variable-from-jade-template-file-to-a-script-file) – Peter Lyons Nov 13 '13 at 00:34
  • So there the answer provided was loginName="#{login}"; which holds good when login is a string. like my examples. But I faced an actual problem when data is an actual object. Like JSON ojbect. I was not able to retrieve that object. – Arvin Gopi Nov 13 '13 at 00:40
  • Peter Lyons, I have modified the question to reflect as such – Arvin Gopi Nov 13 '13 at 00:43
  • 2
    Perhaps use `res.render('index', {data: JSON.stringify({'hello':'world'})});` in your index.js – Peter Lyons Nov 13 '13 at 00:55

1 Answers1

0

In your index.js file:

res.render('index', {data:JSON.stringify({'hello':'world'})});

in your Jade Template:

script(type="text/javascript").
  var data = !{data};

That'll give you an object in the client-side JavaScript.

Jason Nichols
  • 3,739
  • 3
  • 29
  • 49