如何在play framework 2.5中的视图中调用控制器类

时间:2016-12-09 08:31:59

标签: playframework playframework-2.0

我有一个控制器类,如下所示

class MenuAccessor @Inject()  extends securesocial.core.SecureSocial{
  def findAllMenus(): List[Menu] = {
  MorphiaHelper.datastore.find(classOf[Menu]).order("+order").toList
  }
}

我曾经直接在play 2.3.x中的视图中将其称为

  @for(menu <- MenuAccessor.findAllMenus()) {
                    <li class="@menu.menuliclass">

这是否意味着我必须创建路由才能在Play 2.5中调用它?

1 个答案:

答案 0 :(得分:0)

Routes will help you only if you want to get a link to the action (i.e. reverse routing).

You want to get data from some static method - then just call it from the template. Something like this (do not forget packages):

object MenuAccessor{
  def findAllMenus(): List[Menu] = {
    MorphiaHelper.datastore.find(classOf[Menu]).order("+order").toList
  }
}

....

@for(menu <- MenuAccessor.findAllMenus()) {
                <li class="@menu.menuliclass">

However, I prefer to pass parameters as it described in the documentation:

@(products: List[Product])

<ul>
@for(p <- products) {
  <li>@p.name ($@p.price)</li>
}
</ul>

Play 2.5 is all about injection, so getting some data from the static objects or function is not a good idea for the future. Better to refactor your code to pass data as parameters into a template.

If you want "to avoid passing parameters everywhere in play2", then look this very good answer How to avoid passing parameters everywhere in play2? (it's old but still usable)