0

我尝试做一个 PlayFramework 教程,但我失败了。

index.scala.html:

Compilation error

not found: type Customer

In C:\test\app\views\index.scala.html at line 2.


@main("welcome") {
@(customer: Customer, orders: List[Order]) 

<h1>Welcome @customer.name!</h1>

<ul> 
@for(order <- orders) {
<li>@order.getTitle()</li>

} 
</ul>
}

应用程序.java:

public static Result index() {

response().setContentType("text/html");
return ok();

}

请回答。谷歌搜索太多,但我不能。

4

1 回答 1

0

好像您忘记导入模型了。@main尝试在事情之前添加这个:

@import your.package.Customer
@import your.another.package.Order

或者您可以像这样导入整个包:

@import your.package._

编辑:是的,我想这行@(customer: Customer, orders: List[Order])应该是你视图中的第一行,而不是@main行之后,所以它可能应该是这样的:

@(customer: Customer, orders: List[Order]) 

@import your.package._

@main("welcome") {

    <h1>Welcome @customer.name!</h1>

    <ul> 
      @for(order <- orders) {
        <li>@order.getTitle()</li>
      } 
    </ul>
}

在您的Application.java中,您需要将customerorders参数传递到视图中:

 public static Result index() {

   response().setContentType("text/html");
   return ok(index.render(SomeService.instance().getCustomer(), SomeAnotherService.instance().getOrders()));
 }

编辑 2:好的,这就是你可以这样做的方法。

Customer 和 Order 类可能在同一个包中,模板中的导入与简单的 java\scala 导入完全相同。

例子:

客户.java

package models;

public class Customer {
    public String name; //as you use @customer.name thing, the field should be public
}

订单.java

package models;

public class Order {
    private String title; //we can make it private because you use the getter in the template

    public String getTitle() {
         return this.title;
    }

    public void setTitle(String title) {
         this.title = title;
    }
}

应用程序.java

 import models.*;
 import static java.utils.Arrays.*;

 ....

 public static Result index() {

    response().setContentType("text/html");
    Customer customer = new Customer();
    customer.name = "serejja";
    Order order1 = new Order();
    order1.setTitle("my order 1");
    Order order2 = new Order();
    order2.setTitle("my order 2");
    java.util.List orders = asList(order1, order2);
    return ok(index.render(customer, orders));
 }

index.scala.html

@(customer: Customer, orders: List[Order]) 

@import models._

@main("welcome") {

    <h1>Welcome @customer.name!</h1>

    <ul> 
      @for(order <- orders) {
        <li>@order.getTitle()</li>
      } 
    </ul>
}
于 2013-09-10T08:11:56.193 回答