0

I am trying to pass a 2d array of false values from an index.js file of my project to a script section of an ejs file.

index.js

app.get('/nextpage',(req,res)=>{
    var arr = function I have to make a 2d array ;)
    res.render('pages/nextpage.ejs',{
        arr: arr
    });
});

based on a few stack answers from others' related posts, I tried the following implementation in my ejs file:

nextpage.ejs

<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>

    <div id = "script" arr= "<%=arr%>" ></div>
    <script>

        function renderBlock(){
             var arr = document.getElementById("script").getAttribute('arr');
             console.log(arr.length);
             $("#blockView").empty();
             for (var i=0; i <  arr.length;i++){
                for (var j=0; j <  arr[0].length;i++){
                    $('#blockView').append('<button>'+arr[i][j]+'</button');
                }
             }
         }
         renderBlock();

     </script>

I thought I was close. I tried to pass in a 3x3 array and this is what I got:

instead of rendering a button for each value in the 2d array, it renders a button for each character in the string. What I am looking for is the ability to display buttons for each entry of the 2d array. More specifically, how do I allow the script tag of an ejs file to have access to the same variables that the rest of the file has access to?

2
  • data-arr= "<%=arr%>" and var arr = document.getElementById("script").dataset.arr; Commented Mar 19, 2019 at 18:32
  • Put the array directly into your script, rather than an attribute of an element. Commented Mar 19, 2019 at 18:34

1 Answer 1

1

If you pass data from backend to frontend, you have to properly serialize it, usually as JSON:

 "<%=JSON.stringify(arr)%>"
// ->
var arr = JSON.parse( document.getElementById("script").getAttribute('arr'));

But that is just ugly. Why not just directly generate the buttons with EJS?:

<% for(const sub of arr) { %>
  <% for(const el of sub) { %>
    <button> <%= el %> </button>
  <% } %>
<% } %>
Sign up to request clarification or add additional context in comments.

1 Comment

Your first solution definitely works! I am trying to make each button into its own custom query, and their place in the array determines what their query is. Thank you!!!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.