如何使用Play Frame工作迭代?

时间:2013-09-10 07:27:08

标签: playframework-2.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>
}

Application.java:

public static Result index() {

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

}

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

1 个答案:

答案 0 :(得分: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导入完全相同。

示例:

Customer.java

package models;

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

Order.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;
    }
}

Application.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>
}