0

Why doesn't this work?

music.js

var files = fs.readdirSync('public/mymusic');
view.render('music', {mydata: files});

music.jade

script(type='text/javascript').
  for (var i=0; i<mydata.length; i++) {
  console.log(mydata[i]);
  }

ReferenceError: mydata is not defined

This link seems to say I need to stringify and then parse the object, but then I no longer have the original array. how to pass an array of objects to jade template?

Community
  • 1
  • 1
dennis
  • 153
  • 2
  • 9

1 Answers1

1

Are you sure you want to output a block of Javascript code to be ran client-side?

If that's so, you have to define the variable in the client-side Javascript:

script(type="text/javascript").
  var mydata = !{JSON.stringify(mydata)}
  for (var i=0; i<mydata.length; i++) {
    console.log(mydata[i])
  }

The data you pass to your Jade view engine is not shared between client-side & server-side code.

Sven
  • 5,155
  • 29
  • 53
  • Thanks. That works. I thought I'd tried every possible combination, but I guess not. I think I had too many JSON.stringify and JSON.parse statements in my testing code. As way of explanation, I'm trying to insert code in JPlayer's client side javascript to play files in a particular directory. I wanted to disrupt their code as little as possible, so I just wanted a "for loop" in their code to add songs to the list. – dennis Feb 24 '16 at 18:26