0

I use node.js, express.js and pug/jade.

In my server I populate a view with a variable pageId.

I use this variable in my pug view with

script.
  document.addEventListener('DOMContentLoaded', function () {
    var pageId = '#{pageId}';

    (...)

The problem is that I want this script code to be located in a separate file rather than in my view.

So I want to include the script with

script(src='js/my_script.js')

but then I am not able to get the value of the variable in the script.

How is this normally done? It seems wrong to send variables from the server to a script code in the view on the client side.

I guess it is irrelevant that I use pug.js, since the same problem must arise even in plain html.

Jamgreen
  • 10,329
  • 29
  • 113
  • 224
  • ``, or ajax. You could have your server-side code parse all .js files, but... no. Is the pageId not in the url? – Kevin B Sep 20 '16 at 19:22
  • Yo should look into stuff like webpack or the npm module "config". See this question as well http://stackoverflow.com/questions/30030031/passing-environment-dependent-variables-in-webpack – NicolasMoise Sep 20 '16 at 19:26
  • It's actually more than just `pageId`. It is also a lot of data in json format which I use to draw a `d3.js` graph. So on one page, I get some data in json format, and on another page, I get some other data in json format. So it is not possible to hardcode the data directly in the `.js` file. – Jamgreen Sep 20 '16 at 19:40

1 Answers1

0

You can define a global function that receives data in your client-side JS file and then call that function from an inline script on the server-rendered page.

For example, in script.js:

function logPageId(id) {
  console.log(id);
}

Then in your server-rendered page:

<html>
  <body>
    <script src="script.js"></script>
    <script>
      logPageId('somePageId')
    </script>
  </body>
</html>

You would be able to do the same with a JSON string as input.

Robin Murphy
  • 329
  • 2
  • 7