1

I am trying to loop through the object that is coming from app.js. I am using each loop in PUG/JADE, so that I can use its value to print some values. But the li is not getting the value of loop variable

Note : I am getting 'post.title' and 'post.body' below 4 times because, it's coming from the mongo database and I did exactly 4 entries in the database. Plus this also means that object is correctly coming to the index page, but li is not getting the value of loop variable.

Output I am getting

 . = post.title
 . = post.body
 . = post.title
 . = post.body
 . = post.title
 . = post.body
 . = post.title
 . = post.body

What I want

 Title of the post
 body of the post

 Title of another post
 Body of another post

 and so on....

My Code

---- index.pug ----

block content
    ul
    each post in posts
        li = post.title
        li = post.body

---- app.js ----

let Post = require('./models/post');

app.get('/', function(req, res){
   Post.find({}, function(err, posts){

   if(err){
       console.log(err);
   } else {
      res.render('index', {   
        title:'Posts',
        posts: posts
     });
   }
 });
});

What Else I tried

I made a constant array just above the loop to check and iterated through that array. But it gave me the same result as

. = name
. = name
. = name

don't know why. The code for that is below.

block content
     - const names = ["Sami", "Abeer", "Hassaan"];
     ul.list-group
         each name in names
            li = name
Sami
  • 466
  • 1
  • 5
  • 12

1 Answers1

5

Remove the space between li =, so you get li= name. The space indicates that the equal sign should be content of the tag.

Full example of your index.pug:

block content
    ul
    each post in posts
        li= post.title
        li= post.body
Torbjørn Angeltveit
  • 2,232
  • 2
  • 13
  • 10
  • Thanks, it worked perfectly. Don't know why they would not allow space before = sign. it's my programming style to give space before = sign. – Sami May 28 '19 at 19:03
  • 1
    Understable. It's just a pug thing. So you can do: h1 My Super cool header Thats why h1 = <- This is an equal sign would be a string. While: h1= <- this will crash because it expects javascript now – Torbjørn Angeltveit May 28 '19 at 20:12