Braxton C Braxton C - 2 months ago 38
Jade Question

How can I use data passed into jade template in the views javascript?

Rendering Data into template

res.render('account/pets/allPets', { petMap, title: 'All Pets' })

I have tried two thing to make this work

A)

var neighborhoods = [];
for (var i = 0; i < petMap.length; i++) {
neighborhoods.push(new google.maps.LatLng(petMap[i].location.loc[0],pet.location.loc[1]))
}


B)

var neighborhoods = [
each pet in petMap
new google.maps.LatLng(petMap[i].location.loc[0],pet.location.loc[1])
]

Answer

Assuming patMap is a javascript object, you are required to do a few hacky things to make this work. Pug renders serverside, while javascript on the client, so you cannot directly access a pug variable in JS. What you CAN do is convert your js object into a string when the pug compiles, then parse it to JSON when the client executes.

var petMap = JSON.parse(("#{JSON.stringify(petMap)}").replace(/&quot;/g, '"'));
/*
    Let me break this down in terms of execution
    "#{JSON.stringify(petMap)}" -> executes server side, converts #{} accesses pug variable petMap, which has been converted to an object
    .replace(/&quot;/g, '"') -> replaces quote escape sequences (something html does for security) back to quotes so JSON can be parsed
    JSON.parse -> parses json from stringified json the server sent to the client
*/ 
Comments