我尝试做一个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();
}
请回答。很多谷歌搜索,但我不能。
答案 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 中,您需要将customer
和orders
参数传递到视图中:
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>
}