如何使用Jade迭代数组创建一个html表

Paq*_*oft 23 node.js express pug

我从node expressjs框架开始,我遇到了这个我无法解决的问题.

我正在尝试显示一个包含一些博客文章的表(是的,一个博客......),但我没有完成它.

这是Jade模板代码:

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}
Run Code Online (Sandbox Code Playgroud)

这是HTML输出:

<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>
Run Code Online (Sandbox Code Playgroud)

那么,有什么想法吗?

Paq*_*oft 33

我发现问题是我错过了每个TR的TD标签.所以玉代码应该是这样的:

div
  table
    thead
      tr: th Posts
    tbody
      each post, i in userPosts
        tr
          td 
            a(href='/admin/post/' + post.id) #{post.author} - #{post.title}
Run Code Online (Sandbox Code Playgroud)


Cha*_*nce 7

试试这个

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}
Run Code Online (Sandbox Code Playgroud)

  • 什么意思:在tr旁边? (2认同)