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

257
Visualizações
How to use node.js var in pugs java script?

I am passing a variable from my server-side (node)file to my client-side pug file-

const prods_arr = [
   {Types: "Electronic",Brand: "Apple", Products: [ "MacBook Pro", "MacBook Air", "Mac Mini"]}, 
   {Types: "Electronic", Brand: "Dell", Products: [ "Inspioren", "Latitude"]},
   {Types: "Electronic", Brand: "Samsung", Products: [ "Galaxy S20", "Galaxy S10"]}
];

res.render("./products", {
     pageTitle: "products",
     prods: prods_arr
});

I am displaying the content of prods array in the pug file -

select(name="type" onchange="change()")#type
    option(value="Null") "Type"
    for (products in prods) {
        option(value=products.Type) #{procucts.Type}
    }

select(name="brands")#brands
     option(value="Null") "Brand"
     

Now I want to use the prods array inside the script tag.

script.
    function change() {
        var type = document.getElementById("type").value;
        var brand = document.getElementById("brands");
        
        for (brands in prods) {
            if (brands.Type == type) {
                const brandOption = new Option(brands.Brand, brands.Brand);
                brand.add(brandOption, undefined);
            }
        }
    }

How can I use my prods array in the script tag??

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You have to stringify your array

script.
  function change() {
    const type = document.getElementById("type").value;
    const brand = document.getElementById("brands");
    
    for (const prod of !{JSON.stringify(prods)}) {
      if (prod.Types === type) {
        const brandOption = new Option(prod.Brand, prod.Brand);
        brand.add(brandOption, undefined);
      }
    }
  }

!{JSON.stringify(prods)} returns a verbatim JSON string of the array and you can use JSON as object/array literals in JavaScript.

The output is

<script>function change() {
  const type = document.getElementById("type").value;
  const brand = document.getelementById("brands");
  
  for (prod in [{"Types":"Electronic","Brand":"Apple","Products":["MacBook Pro","MacBook Air","Mac Mini"]},{"Types":"Electronic","Brand":"Dell","Products":["Inspioren","Latitude"]},{"Types":"Electronic","Brand":"Samsung","Products":["Galaxy S20","Galaxy S10"]}]) {
    if (prod.Types === type) {
      const brandOption = new Option(prod.Brand, prod.Brand);
      brand.add(brandOption, undefined);
    }
  }
}</script>

You have multiple other errors in your code. This is the working code

select(name="type" onchange="change()")#type
    option(value="Null") Type
    each prod in prods 
      option(value=prod.Types) #{prod.Types}

select(name="brands")#brands
     option(value="Null") Brand

script.
  function change() {
    const type = document.getElementById("type").value;
    const brand = document.getElementById("brands");
    
    for (const prod of !{JSON.stringify(prods)}) {
      if (prod.Types === type) {
        const brandOption = new Option(prod.Brand, prod.Brand);
        brand.add(brandOption, undefined);
      }
    }
  }
about 4 years ago · Juan Pablo Isaza Relatório

0

You can't do it like that. prods is a server-side variable, you have to tweak it in order to access it from client-side. The best suggestion would be not to do that. However, the tweak would be to render it as JSON string in the HTML before you send it to the client, and then read that in the client-side JS.

Example:

<meta name="prods" content="{{ JSON.stringify(prods) }}">
const prods = JSON.parse(document.querySelector('meta[name="prods"]').content);
console.log(prods);
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