Chartjs-How do I use for loop inside script tag in ejs

0๐Ÿ‘

In a similar situation i used this inside script tags and worked!
So try the following and check if it works.

<script type="text/javascript">
   <% data.forEach(function (d) { %>
       console.log("<%= d %>"); // or anything you want to do.    
   <% }) %>
 </script>

Also there is a mistake in your following loop code. Care about opening and closing ejs tags. In the first line you forgot to close the ejs tag.

<% for(var i = 0; i < 5; i++) {
<%= data[i].temperature %>
<% }%>

Use this: <% for(var i = 0; i < 5; i++) { %>

0๐Ÿ‘

I was trying to get property images from my db this way:

<script>
     let data= JSON.parse('<%-JSON.stringify(property)%>')
     let dataArray= [];
              for (var i = 0; i < data.length; i++) {
                let image = data[i].image_name
                dataArray.push({
                  id: i, src: '/uploads/properties/' + image
                })
    
              }
</script>

0๐Ÿ‘

I have a MongoDB database and I wanted to sum up all the prices of items that the customer added to his shopping cart I needed the answer that you asked so I tried the above examples even if they work fine it gives red underlines to the codes. So you must quote the code if you are going to use the variables that come from the server side. This way you donโ€™t get any red underlined code and it looks perfectly fine.

 <script>
    let prices = []
    let pricex;
    let sum = 0;
 " <% for (let i = 0; i < products.userCart.length; i++) { %>"

        pricex = "<%= (products.userCart[i].quantity *  
        products.userCart[i].price) %>";

        prices.push(pricex);
    
   " <%    } %>"

    for (let i = 0; i < prices.length; i++) {
            sum = sum + parseInt(prices[i]);
        
    }

    console.log(sum);
</script>

Leave a comment