Musti
Musti

Reputation: 139

Using Controller Methods in View - Play Framework - Scala

I have got to use the Play Framework on a Web-Project, in which i have to connect the view with the controller classes. Meaning, that i have to use methods, which were declared in the controllers (scala), in the view (scala.html). I really don't know how. I've tried things like

     @controller.class.method()

but it didnt work. I've looked it up, but found nothing, maybe because it's too simple, that anyone would ask about it..?

I appreciate the help.

Upvotes: 2

Views: 2557

Answers (2)

Rhys Bradbury
Rhys Bradbury

Reputation: 1707

You can access reverse routes in your template via:

@routes.controllersFolder.MyControllerName.endPointName

This will resolve to the route.

eg routes file:

GET   /myApp/endpointExample  controllersFolder.MyControllerName.endPointName

so

@routes.controllersFolder.MyControllerName.endPointName

would resolve to:

/myApp/endpointExample

If you're looking to use that on client side for AJAX I would highly recommend JSRoutes.

If you want to have the functionality of a controller then you should have it decoupled in a module eg:

trait MyTrait {
  def add(x: Int, y: Int): Int = x + y
}

@Singleton 
class MyClass with MyTrait

@Singleton
class MyController @Inject() (myClass: MyClass) extends Controller {
  def endPointName(x: String, y: String): Action[AnyContent] = {
    try {
      Ok(
        Json.toJson(
          Json.obj(
            "result" -> myClass.add(
              x = x.toInt,
              y = y.toInt
            )
          )
        )
      )
    } catch {
      case e: NonFatal => BadRequest(
        Json.toJson(
          Json.obj(
            "error" -> e.getMessage
          )
       )
    }
  }
}

You could then refer to the logic of MyClass, without having to form a request, decoupling the logic like so:

@Singleton
class MyOtherController @Inject() (myClass: MyClass) extends Controller {
  def myHtmlPage(): Action[AnyContent] = {
    views.html.myView(myClass)
  }
}

in HMTL

myView.scala.html:

@(myClass: MyClass)

@myClass.add(1, 2) // = 3

I hope this helps, Rhys

Upvotes: 2

Jerry
Jerry

Reputation: 492

If you want to call the controller in views, you should do it with the help of reverse routes

Assuming that your routes is defined like this

GET   /hello/:name          controllers.Application.hello(name)

In the views, you can call it using the following code

@routes.Application.hello("test")

Good luck with you

Upvotes: 1

Related Questions