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.