AbGeMarst
AbGeMarst

Reputation: 166

How do I import variables from NodeJS to JS?

How can I use static variables in an JS file?

I'm using nodeJS with ejs templates. In HTML it works if i use <%= colors %> but i want to use the content of color in clientside js.

i think it should look like:

var color[] = <%= colors =>

would be nice to know what im doing wrong. Thank you!

Marius

edit: to clear things up, i've written the question fast so it seems i've forgotten to explain some things.

colors is an array send by the nodeJS express server.

var colors = ['blue', 'red', 'green'];

in the index.ejs template, i can call "blue" via:

<span>    
  <%= colors[0] %>
</span>

. now i have a separate client-side functions.js file. i want to access "blue" in this file.

Upvotes: 1

Views: 83

Answers (2)

AbGeMarst
AbGeMarst

Reputation: 166

Okay, i found a workaround.

i have now this in my index.ejs template:

<script>
  var colors = [<%= colors %>];
</script>

and i call my functions.js (client-side) in the next line. now i can use:

$("span").text(colors[0]);

. if there's a better solution (the jquery code isnt exactly what i've used), please comment!

Upvotes: 0

Quentin
Quentin

Reputation: 943578

Your first problem is that var color[] = is not valid JavaScript.

You seem to be getting it mixed up with PHP. The syntax you are looking for is probably:

var color = [];
color.push(someValue);

We can't tell what your server side code is going to output for <%= colors => but I'll bet it is something like blue.

var color = [];
color.push(<?= colors =>);

would therefore give you:

var color = [];
color.push(blue);

… which is fine, so long as you have a variable called blue already. You probably want a string literal there, so you need to encode your text as JavaScript literals.

That is more or less the same as JSON so:

var color = [];
color.push(<?= JSON.stringify(colors) =>);

… will probably do the job.

If colors isn't blue but is actually an array, then you would probably want to just dump the whole thing to the variable in one go:

var color = <?= JSON.stringify(colors) =>;

Upvotes: 4

Related Questions