0
votes

Is it possible to access Play Framework scala contoller variables wihout passing to scala.html template?

For example my controller code as below,

    def index = Action { request =>
    val orgId = '12132132'

    Ok(views.html.index(request))
    }

My index.scala.html as below,

    @(implicit request: RequestHeader)
      @main("Test") {

    I want to access controller "orgId" variable here wihtout passing here.

         }

Here is my main.scala.html,

    @(title: String)(content: Html)
<html lang="en">
    <head>
        <title>@title</title>
    </head>
    <body>
        @content <!-- index.html placed here --> 
    </body> 
    <div>
        Here I have bootstrap side menu and I want to display controller variable here without passing to main.scala.html templete.
    </div>
</html> 

Thanks.

1
No, Basically I would have made my request in controllers as an implicit and pass orgId as an argument, and if there are more number of fields then make a case class and pass the instance of that case class in it. - curious
Hi, in my case it is not possible. I have main.scala.html and I have already passed index.scala.html as @content:html parameter. I want to access controller variable on bootstrap modal which is another <div> in my main.scala.html and I can't pass another case class as parameter to my main.scala.html. - Nishan
can you please pase some more code for your index and main html files. - curious
Impossible.. breaks MVC pattern, tight coupling.. - Michael Zajac

1 Answers

0
votes

You cannot do it since it private for the function. No other function can access it (even not in the same class).
If you are using object as instance of the controller (instead of class) and you use value of the object itself then you can do it, but It HIGHLY NOT recommended. e.g.

object MyController extends controller {
  val orgId = '12132132'
  def index = Action { request =>
    Ok(views.html.index(request))
  }
  ...
}

@(implicit request: RequestHeader)
  @main("Test") {

I want to access controller "@{MyController.orgId}" variable here without passing here.

}

If you need to pass some data that isn't depend on the request, meaning it can be value of the object, then it also may be outside the controller. So you can create an object that will hold those values, and access them.
Technically it the same as use the controller, but logically it better separation.