0

I am making a node express app. I am trying to pass a value from jade to a javascript file.

On the server side I am using:

res.render('index', { title: 'Title', test: 1 });

In my index.jade file I have the following:

script(type='text/javascript', src='http://code.jquery.com/jquery-1.9.1.js')
script(type='text/javascript', src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/jquery-ui.js')
script(type='text/javascript', src='./javascripts/ui.js')
script(type='text/javascript', src='./javascripts/handle.js').
  var data = !{test}
block content
  h3= title

In my handle.js file I have

$(function() {

    console.log(data);
});

On the console I get a message saying data is not defined. How do I pass the value of test from the jade file to the javascript file? Currently test is just an interger, but eventually it will be an object which contains a lot of properties.

How do I properly pass the value from the jade file to the javascript file?

RagHaven
  • 4,156
  • 21
  • 72
  • 113
  • You'll have to use a separate `script.` for inline scripts. [Inline Script with SRC Attribute?](http://stackoverflow.com/questions/1056325/javascript-inline-script-with-src-attribute) – Jonathan Lonowski Jun 16 '14 at 19:18
  • That response seems to say that I cannot have an inline source and use the src argument at the same time. So, how am I supposed to pass the value from the jade file to the js file? – RagHaven Jun 16 '14 at 19:22
  • How do I make it such that the variables defined in the inline script are associated with the javascript src file(in this example, it is handle.js) – RagHaven Jun 16 '14 at 19:26

1 Answers1

0

That will only work for literals. For objects you can do this:

var data = !{JSON.stringify(data)};

As for the showing undefined part, check if its getting properly set and it is the correct variable.

Make sure you are loading in correct order:

script(type='text/javascript')                                                   
  var data =!{JSON.stringify(test)};
script(src='./javascripts/handle.js)  
user568109
  • 47,225
  • 17
  • 99
  • 123
  • I tried this, and I still get an error saying data is an unreferenced type. – RagHaven Jun 17 '14 at 19:41
  • I'm still getting an unreferenced error with the new answer – RagHaven Jun 19 '14 at 08:16
  • @AndroidDev93 Are you sure it is getting passed, try printing on the html and post the result in question. – user568109 Jun 19 '14 at 08:42
  • I am printing out the values in HTML. When I do JSON.stringify(test) through HTML and then iterate through the properties I am able to print out the various properties. But when I try to do the same through javascript, it isn't working. Printing data returns undefined. – RagHaven Jun 25 '14 at 01:12