【问题标题】:Play framework: How do I print index number inside scala template by using map播放框架:如何使用 map 在 scala 模板中打印索引号
【发布时间】:2013-11-19 21:53:45
【问题描述】:

嗨,我是 play framework 和 scala 的新手,继续我正在阅读 play 文档,但是在 scala 模板文件中的地图内打印索引时遇到问题。我试过下面的代码,但它不适合我。

//尝试1:但不工作

@(customer: Customer, orders: Seq[Order])
<h1>Welcome @customer.name!</h1>

<ul> 
@orders.map { case(index,order) =>
  <li>@index</li>
  <li>@order.title</li>
} 
</ul>

//尝试2:但不工作

@(customer: Customer, orders: Seq[Order])
<h1>Welcome @customer.name!</h1>

<ul> 
@orders.map { order =>
  <li>@order.index</li>
  <li>@order.title</li>
} 
</ul>

请为此提供一些解决方案或提供其他参考/资源链接以供我探索更多内容。你可以从play documentation找到上面的例子。

【问题讨论】:

    标签: scala playframework-2.0


    【解决方案1】:

    您可以使用zipWithIndex。它接受一个列表并从中创建一个元组,其中第一部分是列表的元素,第二部分是索引。

    例子:

    @orders.zipWithIndex.map { case (order, index) =>
      <li>@index</li>
      <li>@order.title</li>
    } 
    

    【讨论】:

    • 它显示在顶部compile error: wrong number of parameters; expected = 1
    • 您的zipWithIndex 对象实际上具有什么类型的值?它有一个名为index 的单独对象,例如title ???
    • zipWithIndex 获取一个列表并将其与索引配对。这意味着如果你有一个Seq[Order],那么你会得到一个Seq[(Order, Int)],然后我们会在此基础上使用case 提取器将它们分开:case (order, index) =&gt;。你的错误信息似乎是别的东西。你正确地调用你的观点吗?我回家后可以试试这个。
    • 哦,它现在工作正常......谢谢......实际上我不知道zipWithIndex,所以我手动创建它,这就是它不起作用的原因。
    • 是的,这是 Scala 内置的集合函数。
    猜你喜欢
    • 2013-10-10
    • 2013-09-22
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    • 1970-01-01
    • 2019-02-07
    • 1970-01-01
    • 2014-05-03
    相关资源
    最近更新 更多