'how do I use for loop inside script tag in ejs

I try to draw chart, using chart.js.

To get my data, I try to use ejs tags

for example, in ejs I input html like this, and it works well.

      <p>date: <%= today %></p>
  <p>temperature: <%= data[data.length-1].temperature %>℃</p>

  <h1>5days average temperature</h1>

  <ul>
    <% for(var i = 0; i < 5; i++) {(function (j) {%>
      <li><%= dateList[j] %>%></li>
      <ul><li><%= avgLocTmpList[i] %></li></ul>
    <% })(i);} %>
</ul>

but when I use chart.js, I have to use ejs tags like this inside .

<script>
        var temper0 = '<%= data[0].temperature%>';
        tempList.push(temper0);
        var temper1 = '<%= data[1].temperature%>';
        tempList.push(temper1);
        var temper2 = '<%= data[2].temperature%>';
        tempList.push(temper2);
</script>

I can get data[0].temperature as well inside tag.

but, I hope to use for loop inside . such as

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

but I can't handle this. Is there any option or way to handle this for loop inside ??

Thanks, in advance.



Solution 1:[1]

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++) { %>

Solution 2:[2]

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>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Panda