Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass optional parameter to scala template in play framework 2

Is it possible for the java controller in playframework 2 to pass optional parameter to the scala page?

I have a scala page which I'm rendering from different actions. only in a certain case one of these actions is supposed to pass a parameter to the scala, do i have to change every render call? basically i want to call template.scala.html in 2 ways

template.render(msg) //java

and

template.render()//java

where in my template i have this: @(msg:String = "xyz")

currently i get an error for call with no message that it doesn't render(java.lang.String) in views.html.template cannot be applied to ()

like image 216
nightograph Avatar asked Dec 09 '22 17:12

nightograph


2 Answers

As a work-around you could store your parameter in the Context.args map. It's a Map<String,Object> so you can store anything that's needed for the current request.

That's an easy way of making values accessible in your templates without having to declare/pass them as parameters.

Controller

public static Result someAction()
{
  ctx().args.put("msg", "Hello world!");

  return ok(myview.render());
}

template

@if(ctx.args.containsKey("msg")){
  <p>@ctx.args.get("msg")</p>
}
like image 100
estmatic Avatar answered May 10 '23 23:05

estmatic


In Play Framework 2 for Java the controller have to pass a default value or null. In other templates you can leave the optional parameter away.

like image 40
gfjr Avatar answered May 11 '23 00:05

gfjr