skip to Main Content

I want to pass a variable from Node.js to the internal JavaScript that is inside "flashcards", I am trying to use EJS to pass the array "cardNames"

Server side:

app.get("/apps/flashcards", (req, res) => {
    res.render("flashcards", { cardNames: ["card1", "card2", "card3", "card4"] });
})

In my "flashcards" EJS file I have four span elements, all of which have the same class ("my-cards"). I want to change their textContent as shown below:

Client side (flashcards file):

<script>
const cardNames = <% cardNames %>
const cards= document.querySelectorAll(".my-cards");
for (let i = 0; i < cards.length; i++) {
    cards[i].textContent = cardNames[i] + ", Score: 0";
}
</script>

I get an error:

"Uncaught SyntaxError: Unexpected token ‘const’"

How can I send a file from Node.js to the internal or even external JavaScript? The logic MUST be separate from the html elements so it doesn’t get confusing.
It doesn’t have to be EJS, I’m willing to use other methods as long as I can achieve results.

3

Answers


  1. you first get the variables and then simply pass then like this

    and also you got the error coz you are accessing it in wrong way, as when this variable is reaching in ejs it will be in string so first convert that variable to array first like this
    const cardNames = <% cardNames %>.trim().split(",")

    app.get("/apps/flashcards", (req, res) => {
        const cardNames = ["card1", "card2", "card3", "card4"];
        res.render("flashcards", { cardNames });
    });
    Login or Signup to reply.
  2. To pass a variable from Node.js to JavaScript, you can do so by embedding the JavaScript code within your Node.js script or by using a Node.js library like vm (Virtual Machine) or node-ipc (Inter-Process Communication).

    Login or Signup to reply.
  3. try

    <script>
    var cardNames = <%= cardNames %>
    var cards= document.querySelectorAll(".my-cards");
    for (var i = 0; i < cards.length; i++) {
        cards[i].textContent = cardNames[i] + ", Score: 0";
    }
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search