node.js 如何使用 Jade 迭代数组创建 html 表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7921556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:42:00  来源:igfitidea点击:

How to create an html table with Jade iterating an array

node.jsexpresspug

提问by PaquitoSoft

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

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

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:

这是 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}

And this is the HTML output:

这是 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>

So, any ideas?

那么,有什么想法吗?

回答by PaquitoSoft

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

我发现问题是我缺少每个 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}

回答by Chance

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}

回答by Nikolas H

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