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

480
Visualizações
How to pass variable from js to pug

My problem is that I cannot seem to modify the variable that the pug file uses to loop.

section.p-0.md-p-5.muli
    .flex.flex-wrap
      script.
        var users2 = '#{users}';
        console.log(users2);
        /*
        const searchBar = document.getElementById('searchBar');
        searchBar.addEventListener('keyup', (e) => {
          const search = e.target.value;
          const filteredFiles = users2[0].filter(user => {
            return user.toString[0][0].includes(search);
          })
          console.log(filteredFiles);
        });
        */
      each user in users2
        .w-100pc.md-w-33pc.p-10
          a.block.no-underline.p-5.br-8.hover-bg-indigo-lightest-10.hover-scale-up-1.ease-300.filePage(href=`/${user.slug}`)
            img.w-100pc(src=`${user.photoUrl[0]}` alt='')
            p.fw-600.white.fs-m3.mt-3
              | Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed…
            .indigo.fs-s3.italic.after-arrow-right.my-4 3 days ago by Jeff

In the 3 line I have a script tag that sets a passed in array of objects. Than I want to modify those objects and pass the new filtered array to loop on line 16. However, I do not know how to pass the variable from line 4 to line 16. When I run the code I get the error "Cannot read property 'length' of undefined". Any ideas on how to fix this? Thanks.

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

0

At all times, you must be very clear about what is on the server and what is on the client.

The server (ie Pug) computes and generates the Html output. At this server stage, there is no browser in existence. Any variables used are variables at the server.

When a user launches a browser to access your page, the above generated Html output is received by the browser and any script commands in it then run in the browser. There is no existence of Pug at this time.

users2, contained in a <script> block, is a client side variable. It does not exist when Pug is running.

users is a server side variable, and is thus available to the Pug code.

The error message you get can be fixed with a simple change: each user in users.

//-Your `users` object is a SERVER variable.

script.
  var users2 = '#{users}';
  console.log(users2);
  //-The above, other than the substitution of #{users}, DO NOT RUN AT THE SERVER

//-The below runs ONLY at the server, thus object `users` is available
section.p-0.md-p-5.muli
  .flex.flex-wrap
    each user in users
      .w-100pc.md-w-33pc.p-10
        a.block.no-underline.p-5.br-8.hover-bg-indigo-lightest-10.hover-scale-up-1.ease-300.filePage(href=`/${user.slug}`)
        img.w-100pc(src=`${user.photoUrl[0]}` alt='')
        p.fw-600.white.fs-m3.mt-3
          | Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed…
        .indigo.fs-s3.italic.after-arrow-right.my-4 3 days ago by Jeff

Fortunately or unfortunately, you didn't use the exact same name for the client variable. It may confuse you thoroughly, or it may enlighten you completely. For example, you could have written the following and it will still work fine:

script.
  let users = '#{users}';
  console.log(users);

section
  each user in users
    img(src=user.photoUrl[0])

OK, now to your requirement to modify users. You can't, if you are thinking of letting the client modify it and then returning to Pug to use the updated value. After the browser receives the Html output, it disconnects from the server. Similarly, when Pug is generating the Html output, the browser does not exist. There is zero interaction between the Pug engine and the browser's Javascript engine!

The commented out code in your client code does not reveal how you want to modify users. What additional information is there on the client that requires you to make the modification in the browser instead of at the server? Is it because you need (a human) user input? You should post another question to describe the interaction you want between browser and server. The answer will probably require Ajax calls or a form submission.

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