Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

169
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!