I have a variable, test, in script.js. I reference script.js in the head of my index.jade document like this: script(type="text/javascript")(src="scripts/script.js").
In my index.jade file, I need to use that test variable, but when I try to, in almost all cases I get an error saying 'test' is not defined.
I've found that something like body(onload="alert(test);") can access the test variable, but something like p #{test} or p= test cannot access it, which is really what I need to work.
So how can I pass a variable from script.js into index.jade so that Jade will recognize it? Thanks in advance for any advice you might have.
This is server side javascript:
- var colors = ['red', 'green', 'blue']
And this is client side:
body(onload="alert(colors);")
Because of this colors on client side is undefined. You can do this:
body(onload="alert(#{colors});")
EDIT:
If colors is client side javascript variable, then you should do it like this:
ul#myul
script
window.addEventListener('load', function(){
var ul = document.getElementById('myul');
for(var i = 0; i < colors.length; i++){
var li = document.createElement('li');
li.innerHTML = colors[i];
ul.appendChild(li);
}
})
EDIT:
test is client side variable and cannot be used as server side js variable. to use it with jade, you should first pass it from server like this in nodejs:
res.render('myviewpath', { test: test });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With