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

171
Visualizações
Error including header.ejs with a db.query inside

All my files are working correctly but if I include a db.query on my header I'm getting this error when I try visualice another ejs:

ReferenceError: D:\Proyects\exampleProyect\views\exampleLayout.ejs:1 

 >> 1| <%- include('layouts/header.ejs', {categories:results}); %>
    2| 
    3|     <div class="container">
    4| 

results is not defined

My code:

index.js

router.get('/', function(req, res, next) {    
  db.query("SELECT * FROM categories",function(err,results){
  res.render('layouts/header', { title: 'HOME', categories:results });
  }); 
});

header.ejs

...
<% for(var i=0;i<categories.length;i++) { %>
    <a href="/categories/<%=categories[i].name%>"> 
        <%=categories.name%>
    </a>
<% } %>
...

exampleLayout.js

router.get('/', function(req, res, next) {    
    db.query("SELECT * FROM examples",function(err,names){   
        res.render('exampleLayout', { title: 'Layout',list:names });
    });       
});

exampleLayout.ejs

<%- include('layouts/header.ejs') %>        
    <div class="container">   
        <% for(var i=0;i<list.length;i++) { %>
            ...
        <% } %>
    </div>

The error happens because I have 2 db.query trying to access into exampleLayout.ejs (first db.query from index.js on header.ejs and the second one from exampleLayout.js)
If I try to include like this:

<%- include('layouts/header.ejs') %> or <%- include layouts/header.ejs %>

I get another error but basically for the same reason. I know my files are correct because all was working until I tried this, so how can I have two db.query from two different .js in the same .ejs?

After trying a few different ways, I found a possible solution with this code:

<%- include('layouts/header.ejs', {categories: list}) %>

exampleLayout.ejs

<%- include('layouts/header.ejs', {categories: list}) %>
    <div class="container">
        <% for(var i=0;i<list.length;i++) { %>
        ...
        <% } %>
    </div>

but I'm not sure if using {categories: list} the include makes sense or not. I would appreciate if someone can explain or show me the correct way to do it.

about 4 years ago · Juan Pablo Isaza
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