0

I have a javascript file "scripts.js" and I have a variable:

var myArray = ["a", "b", "c"];

In my index.pug I tried this:

each n in myArray
  ul
    li n

but it doesn't work.

How can my variable in javascript is recognized in my index.pug?

Thanks.

cabita
  • 832
  • 2
  • 12
  • 36
  • Does this answer your question? [How to pass variable from jade template file to a script file?](https://stackoverflow.com/questions/8698534/how-to-pass-variable-from-jade-template-file-to-a-script-file) – Mote Zart Aug 10 '20 at 21:07
  • Thanks for your answer, but, that is not the same because in this link is about how the variable from .pug is passed to the script file and I need the opposite, I need a variable declared in javascript to be recognized in the .pug. – cabita Aug 10 '20 at 21:11
  • U should be able to pass it in as answer suggests in .js file and then in pug it should be accessible. `res.render( 'index', { myArray: ["a", "b", "c"] } );` – Mote Zart Aug 10 '20 at 21:21
  • Thanks for your answer. My .js file is not a node file, it's only a vanilla javascript. Can I use res.render in this case? – cabita Aug 10 '20 at 21:34
  • Never done myself. It looks like U can maybe do it as show on pug website Overview section: https://pugjs.org/api/getting-started.html. Seems u still need to compile the pug tho with node. – Mote Zart Aug 10 '20 at 21:43
  • I'll review all your comments and the link sent. Thanks. – cabita Aug 10 '20 at 21:59
  • 2
    The `myArray` variable exists in your browser while pug is generated on the server. Without sending the variable back to the server using a form POST the two constructs just can't talk to each other the way I think you're expecting them to. – Graham Aug 11 '20 at 04:34
  • You can do this in js. Just use `forEach` and create `li` elements in it. –  Aug 11 '20 at 15:04

0 Answers0