Zack
Zack

Reputation: 45

Ejs forEach loop is not defined

So here is my problem I am trying to do a forEach in ejs which will render html onto the page. Here is the store page for the ejs forEach loop.

<% include _includes/header.ejs %>
   <div class="container">
     <% cards.forEach( card => { %>
      <% include('_includes/cards.ejs', card) %>
  <% }) %>
</div>
<% include _includes/footer.ejs %>

here is the cards.ejs file

<div class="card" style="width: 18rem;">
  <img class="card-img-top" src='' alt="Card image cap">
  <div class="card-body">
    <h5 class="card-title"><%= titleCard %></h5>
    <p class="card-text"><%= desc %></p>
    <a href="#" class="btn btn-primary">Go somewhere</a>
  </div>
</div>

Here is my express code for the store page

 app.get('/store', function(req, res) {
  res.render('store', {
    user: req.user,
    title: 'Store'});
});

and finally this

cards = [
  {
    titleCard: 'title 1',
    desc: 'just some text'
  },
  {
    titleCard: 'title 1',
    desc: 'just some text'
  },
  {
    titleCard: 'title 1',
    desc: 'just some text'
  },
]

I have tried multiple things and always get the error that cards is not defined. Where am I supposed to put this? I would really appreciate some help on this!

Upvotes: 4

Views: 16443

Answers (2)

Ahmed Hammad
Ahmed Hammad

Reputation: 3085

Here are a couple of things that may help,

1- Make sure you're exporting this cards module in a proper way, basically you cannot just import it without an explicit export.

2- Try to use an object parameter to the include method

<% include('_includes/cards.ejs', {card : card}) %>

I apologize, I can't test it right now, but try this and let me know if it worked.

Upvotes: 1

jfriend00
jfriend00

Reputation: 707148

You have to pass cards to res.render(). You can do so like this:

app.get('/store', function(req, res) {
  res.render('store', {
    user: req.user,
    title: 'Store',
    cards: cards
  });
});

Upvotes: 3

Related Questions