Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

178
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda