花括号必须在同一行@for
@for(product <- products){
如果您在 play 应用程序中使用 java,请注意 scala 模板中的值。例如product.ean
,仅当您在 class 中声明ean
属性时才有效。如果您使用经典 bean,那么您需要编写方法名称,例如public
Product
product.getEan
我对您的代码进行了验证,它可以正常工作:
模型/Product.java
package models;
public class Product{
private String ean;
private String name;
private String description;
public Product(){};
public String getEan(){
return ean;
}
public void setEan(String ean){
this.ean = ean;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getDescription(){
return description;
}
public void setDescription(String description){
this.description = description;
}
}
控制器/Application.java
package controllers;
import play.*;
import play.mvc.*;
import views.html.*;
import models.Product;
import java.util.List;
import java.util.ArrayList;
public class Application extends Controller {
public Result index() {
List<Product> products = new ArrayList<>();
Product product1 = new Product();
product1.setName("p 1");
product1.setEan("ean_1");
product1.setDescription("description 1");
products.add(product1);
return ok(index.render(products));
}
}
配置/路由
# Home page
GET / controllers.Application.index()
视图/index.scala.html
@(products :List[Product])
<h1> All Products </h1>
<table class="table table-striped">
<thead>
<tr>
<th> EAN </th>
<th> NAME </th>
<th> DESCRIPTION </th>
</tr>
</thead>
<tbody>
@for(product <- products){
<tr>
<td><a href="@routes.Application.index()"> @product.getEan </a></td>
<td><a href="@routes.Application.index()"> @product.getName </a></td>
<td><a href="@routes.Application.index()"> @product.getDescription </a></td>
</tr>
}
</tbody>
</table>
结果:
<h1> All Products </h1>
<table class="table table-striped">
<thead>
<tr>
<th> EAN </th>
<th> NAME </th>
<th> DESCRIPTION </th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="/"> ean_1 </a></td>
<td><a href="/"> p 1 </a></td>
<td><a href="/"> description 1 </a></td>
</tr>
</tbody>
</table>