passing an array from EJS to Javascript

前端 未结 5 872
隐瞒了意图╮
隐瞒了意图╮ 2021-01-20 23:48

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 variab

相关标签:
5条回答
  • 2021-01-20 23:53

    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.

    0 讨论(0)
  • 2021-01-20 23:57

    Refer to JSON from EJS to JSON object in JS

    Remove the single quote:

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

    0 讨论(0)
  • 2021-01-21 00:14

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

            var test = <%-JSON.stringify(level_tab) %>; 
            console.log("test :"+test);
    
    0 讨论(0)
  • 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]%>');
    <%}%>
    
    0 讨论(0)
  • 2021-01-21 00:18

    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>
    <% } %>
    
    0 讨论(0)
提交回复
热议问题