Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

238
Views
How can I acess a array from node.js in javacsript with ejs

So I am making a app where it needs to pass an array from the server into the client. I have tried to do

// Server
app.get('/', (req,res) => {
  res.render('index', {
    data: ["Hello"]
  })
})

// EJS
<script>
  const data = '<%- JSON.stringify(locals.data) || [] %>'
</script>

But then its not an array in the ejs so I tried

// Server
app.get('/', (req,res) => {
  res.render('index', {
    data: ["Hello"]
  })
})

// EJS
<script>
  const data = JSON.parse('<%- JSON.stringify(locals.data) || [] %>')
</script>

That worked until I passed an array with a ' in it, is there anyway that I can pass the array into javascript with having problems with having certain charters?

This is working with a discord bot to get the servers and display them on a page. So I want to make sure it can show all the charaters.

And if I change the ' to " or ` it could still cause issues with some inputs.

Thanks.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Thats to @hacKaTun3s for this answer:

const data = <%- JSON.stringify(locals.data) || [] %>

But this causes sytax errors and can be annoying, so i am using this:

EJS:

<p hidden id=scrpt_get_locals><%= JSON.stringify(locals) %></p>

It will be hidden and in the script we will access its contents.

JAVASCRIPT: (DEFER)

const locals = JSON.parse(document.getElementById('scrpt_get_locals').innerText) // Get element text that has locals, then parse it
document.getElementById('scrpt_get_locals').innerText = '' // Remove the text (So we don't have a random element with the locals
document.getElementById('scrpt_get_locals').id = '' // Remove id (Optional)

Edit:

Top access the variable data you would:

console.log(locals.data)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!