How to create an html table with Jade iterating an array
Asked Answered
L

3

25

I'm starting with node expressjs framework and I came across this problem I can't solve.

I'm trying to display a table with some blog posts (yes, a blog...) but I don't get it done.

This is the Jade template code:

div
  table
    thead
      tr: th Posts
    tbody
      each post, i in userPosts
        tr(class=(i % 2 == 0) ? 'odd' : 'even'): a(href='/admin/post/' + post.id) #{post.author} - #{post.title}

And this is the HTML output:

<div>
  <a href="/admin/post/1">Post 1</a>
  <a href="/admin/post/2">Post 2</a>
  <a href="/admin/post/3">Post 3</a>
  <table>
    <thead>
      <tr>
        <th>Posts</th>
      </tr>
    </thead>
    <tbody>
      <tr class="odd"></tr>
      <tr class="even"></tr>
      <tr class="odd"></tr>
    </tbody>
  </table>
</div>

So, any ideas?

Lefler answered 27/10, 2011 at 19:53 Comment(2)
Check out n-th child CSS rules. You don't need to compute even/odd and manually add a class. w3.org/Style/Examples/007/evenodd.en.htmlAuvil
Yes, you're right. But I was using an existing design I dindn't want to change. Anyway, that's not the problem. I already tried to print a classless tr tag and it didn't work either.Lefler
L
34

I found that the problem was that I was missing the TD tag for each TR. So the jade code should be like this:

div
  table
    thead
      tr: th Posts
    tbody
      each post, i in userPosts
        tr
          td 
            a(href='/admin/post/' + post.id) #{post.author} - #{post.title}
Lefler answered 28/10, 2011 at 21:30 Comment(3)
I had to remove the i, and do each post in userPostsLitmus
what is the meaning of : next to tr?Eisenhower
What is the problem in this code. Not making tr for td below th tr. .col-md-12 table.table.table-bordered.table-hover thead tr th No. th Title th Description th Operations - let i=1; each task in tasks tbody tr td #{i++} td #{task.title} td #{task.description} td a(class=${task.status==true ? 'btn btn-success' : 'btn btn-dark'}, href=/turn/${task._id}) DoneCoronograph
F
7

try this

div
  table
    thead
      tr: th Posts
    tbody
      each post, i in userPosts
        tr(class=(i % 2 == 0) ? 'odd' : 'even') 
          td
            a(href='/admin/post/' + post.id) #{post.author} - #{post.title}
Fingerboard answered 27/10, 2011 at 20:0 Comment(2)
I already tried that one. It doesn't work. Thanks for your help.Lefler
what is the meaning of : next to tr?Eisenhower
T
1

With current pug version didn't work for me. Instead I modified the code to the following pattern:

div
  table
    thead
      tr
        th title...
    tbody
      each post in userPosts
        tr
          td= post.author
          td= post.title
Tippler answered 11/3, 2019 at 11:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.