5

I am trying to passe an array from ejs to JavaScript. I can get to the values inside ejs but not from JavaScript. all the time i get undefined because the contents of the variable "test" is a string is not an array.

<script>

var test = '<%- level_tab %>';
alert(test);

function level(s1,s2){
            var s1 = document.getElementById(s1);
            var s2 = document.getElementById(s2);
            s2.innerHTML = "";
            if(s1.value == "level_0"){
                var optionArray = test;
            }
            else if(s1.value == "level_1"){
                var optionArray = ["test|test01", "test0|test02"];
            }
 for(var option in optionArray){
                var pair = optionArray[option].split("|");
                var newOption = document.createElement("option");
                newOption.value = pair[0];
                newOption.innerHTML = pair[1];
                s2.options.add(newOption);
            }
        }
</script>
amine_detter
  • 137
  • 1
  • 1
  • 11

5 Answers5

16

You have to stringify the array

var test = <%- JSON.stringify(level_tab) %>;

I'm not familiar with EJS but in general the same principle should apply even if syntax is slightly different in EJS.

razakj
  • 991
  • 8
  • 11
  • @amine_detter i edited the post - Have you tried removing the quotes? – razakj Jul 04 '16 at 11:00
  • 1
    Great it works now, but the editeur (webstorm) signifies that there is an error that's why i am using the single quotes. any way Thank you. – amine_detter Jul 04 '16 at 12:34
5

Refer to JSON from EJS to JSON object in JS

Remove the single quote:

var test = <%- JSON.stringify(level_tab) %>;

Community
  • 1
  • 1
engineforce
  • 2,840
  • 1
  • 23
  • 17
  • it works, but the editeur (webstorm) signifies that there is an error that's why i am using the single quotes. Thank you – amine_detter Jul 04 '16 at 12:35
2

Use this it will work fine.(Don't use single quotation )

        var test = <%-JSON.stringify(level_tab) %>; 
        console.log("test :"+test);
Shree
  • 145
  • 4
  • 15
1

i found a solution it's work, but i don't know if there is other ways to do it. i change

var test = '<%- level_tab %>';

by this loop,

<% for(var j=0; j<level_tab.length; j++) { %>
            level_tab.push('<%- level_tab[j]%>');
<%}%>
amine_detter
  • 137
  • 1
  • 1
  • 11
0

I process like that to pass array from express to an EJS page: in the node.js code :

.post('/action', function(req, res) {
        var arr = ["premier", "second", "troisième", "quatrieme", "cinquieme"];
        res.render('page.ejs', {arr: arr}); 
});

And in page.ejs :

<% for(var i = 0 ; i < arr.length ; i++) { %>
       <tr>
            <td><%= arr[i] %></td>
       </tr>
<% } %>
kevin ternet
  • 4,514
  • 2
  • 19
  • 27