Voting app. Problem with jade

Hello everyone I’m trying to complete the voting app project.
To begin with I decided to implement simple code taking some numbers from the form and plotting the chart from it.
I dont know if I’m doing it right but I came up with this:

I handle the post request like this:

router.post('/poll_submit', function(req, res)
    {
        //some code
        res.render('poll_submit.jade', {arr: [4, 2, 3, 1]}); //arr should contain numbers from the submitted form  
    });

as you can see I pass the variables through render.

I know I can access the variable the variable in jade template like this

each item in arr
  li #{item}

The problem is I’m struggling to read this variable in js to pass something to google charts. For example
script.

console.log(arr)

returns arr is not defined

Could you please help me or tell if I am completely wrong and there is a much better way to do it because overall all this looks rather ugly.

Hi @AlRum

Any locals you pass into render is only view able by the template whilst it’s being rendered, once it’s turned into an html string and sent to the client, those variables don’t exist.

So the client requests that page from the server, when it gets the html response, it knows nothing about the variables used during rendering.

If you want to send some data down with the html so the client can read it you’ll probably want to do something like:

// express
res.render('poll_submit.jade', { arr: [4, 3, 2, 1], arrForClient: JSON.stringify([4, 2, 3, 1]) })

// poll_submit.jade
body
  ...
  script window.clientState = #{arrForClient};

// client.js
console.log(JSON.parse(window.clientState))

When the client loads the page, it will instantiate a new variable on the window object called clientState, you can then parse this and get access to the array as you expect.

Personally, I’ve never used express’ render function so there may be better ways to do this, but I hope this will give you a head start.

1 Like

@joesmith100

Thank you for the explanation! I don’t insist on using the render function. Could you please tell or give some reference what is the standard way to do such things ?

Render is a good way to do it, what I meant was there might be a better way to inject code meant for the client using render, rather than using a different technique altogether.

Personally I’ve been using react a lot with reacts server rendering to send state to the client.

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.

@joesmith100

could you please help again ?
the method doesn’t seem to work with this code

res.render('poll_submit.jade', {arr:JSON.stringify({'a':'b'})})

Just out of curiosity, why are you using Jade? Jade is now known as Pug, and have you tried updating to the latest version?