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

169
Visualizações
Parameters in Pug template not available for onclick event

I have a pug template test.pug that has a button. When clicked, I want the button to call a function that uses parameters passed to the template from the rendering endpoint. Here is the template:

doctype html
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
    script(type="text/javascript").
        window.addEventListener('DOMContentLoaded', function(){
            document.getElementById('play-button').addEventListener('click', async () => {
                console.log(testvar);
                console.log('ready');
            });
        }, false);
  body
    button(type = 'button' id = 'play-button') Click to play

And here is the endpoint that renders the pug template:

const express = require('express');
const router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) { 
    res.render('test',{
        title:'Player',
        testvar:'testvar'       
    });
});

module.exports = router;

But when I load the page and click the button, I get this error:

Uncaught (in promise) ReferenceError: testvar is not defined
at HTMLButtonElement.<anonymous>

The code works correctly if I comment out console.log(testvar), so I know that the onclick event handler is being added successfully. So apparently the event handler is being added before the parameters are passed to the template.

How can I make the parameters accessible to the onclick event?

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

0

Local variables passed through Express's .render() method are only available to Pug and only available while Pug is being compiled on the server. They don't remain available to client-side javascript once Pug has been compiled to HTML and sent to the browser.

If you want them available client-side, you must use Pug interpolation to define the variable within a script tag, alongside your other client-side javascript.

Assuming testvar is a string, you could approach it like this:

doctype html
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
    script(type="text/javascript").
      const testvar = '#{testvar}'; // interpolate the value from Pug
      window.addEventListener('DOMContentLoaded', function() {
        document.getElementById('play-button').addEventListener('click', async () => {
          console.log(testvar);
          console.log('ready');
        });
      }, false);
  body
    button(type = 'button' id = 'play-button') Click to play

If testvar is an array or object, you'll need to use the JSON.stringify() method to print the array or object into the script tag.

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