简体   繁体   中英

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM