简体   繁体   English

如何在 ejs 文件内的脚本标记中使用此变量

[英]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.名为'classGroup'的变量是在渲染时从服务端文件传递过来的变量,在ejs文件中的html代码中使用ejs语法(<%=%>)很好用,脚本中也用到了标记在同一个 ejs 文件中。

Also, since this variable was paginated using paginate() on the server side, the data array is included in the docs.此外,由于此变量是在服务器端使用 paginate() 进行分页的,因此数据数组包含在文档中。

If you use ejs syntax ( <%= %>) to write this classGroup variable inside the script tag, the 'i' in it is not recognized.如果您使用 ejs 语法 (<%= %>) 在脚本标记内写入这个 classGroup 变量,则无法识别其中的“i”。

How can I get 'i' to work even within <%= %>?我怎样才能让“i”在 <%= %> 内工作?

<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 .您尚未在任何 ejs 标签中定义i ,因此 ejs 对i一无所知。 In simple words, you can't use rendered data with i inside ejs tags.简而言之,您不能在 ejs 标签中使用带有i渲染数据。 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您可以做的是在for循环之前将渲染数据分配给javascript变量,并在没有任何ejs标签的情况下实现for循环

<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.为了将classGroup分配给 javascript 变量,您需要将其呈现为 JSON 字符串。 So inside your controller you have to use this所以在你的控制器中你必须使用它

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

Hope I helped you.希望我对你有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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