Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

180
Views
How can I use this variable in script tag inside ejs file

The variable called 'classGroup' is a variable passed during rendering from the server file, and it was used well in the html code in the ejs file using the ejs syntax ( <%= %>), and it is also used in the script tag in the same ejs file.

Also, since this variable was paginated using paginate() on the server side, the data array is included in the docs.

If you use ejs syntax ( <%= %>) to write this classGroup variable inside the script tag, the 'i' in it is not recognized.

How can I get 'i' to work even within <%= %>?

<script>
    let len = <%=classGroup.totalDocs%>;
     for(let i = 0 ;i < len;i++) { 
           let chunk = <%= classGroup.docs[i].weight %>; // If I put a number in place of 'i', it works, but 'i' doesn't work.
           console.log('weight : ' + chunk);
     }
</script>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You have not defined i inside any ejs tag, so ejs knows nothing about i. In simple words, you can't use rendered data with i inside ejs tags. What you can do is to assign rendered data to javascript variables before the for loop, and implement the for loop without any ejs tag

<script>
    let classGroup = <%- classGroup -%>; // use <%- instead of <%=
    let len = classGroup.totalDocs
    for (let i = 0; i < len; i++) {
        let chunk = classGroup.docs[i].weight;
        console.log('weight : ' + chunk);
    }    
</script>

In order to assign classGroup to a javascript variable, you need to render it as a JSON string. So inside your controller you have to use this

res.render("ejs-file", {classGroup: JSON.stringify(classGroup)});

Hope I helped you.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!