0
votes

I've a more or less general question of understanding the Play framework, regarding the passing of a common state to a template. It's a widely discussed topic, like here: http://jazzy.id.au/default/2012/10/26/passing_common_state_to_templates_in_play_framework.html But still I'm not sure what the best practice is. I'm familiar with scripting language based MVC frameworks, like CakePHP or Django, so this issue never mattered to me. So, basically there are two possibilities:

  • Using implicit variables in the templates, which just works with Scala and you still have to declare that variable in every single template!?
  • Using the Http.Context class to store data, which seems for me more like a hack it not so suitable to pass a lot of data. (Please correct me if I'm wrong)

I have two important use cases for that issue. The first one is having the logged-in user object available everywhere. Thats the pretty easy solvable with the Http.Context. The second one is more difficult for me. I have a header which either displays a login form or some user specific options. Hence I have a if condition in the template, checking if an user is logged in. But when I display the login form I need form object generated in the controller. So I have to generate that object in every single controller and pass it to every single template, although I just need it when no user is logged in. I'm to sure if that is meant like this from the makers of the Play framework.

I would be very glad about any insight or impulse. Thanks.

1

1 Answers

0
votes

For displaying your form, you can just call a method that will create the Form and render a template instead of just calling another template.

For example, you can have a template where you want to display the user information or the form like this :

views/home.scala.html :

...
@if(user.isLoggedIn()) {
  @loggedInHeader()
} else {
  @controllers.Application.loginFormHeader()
}
...

If the user is already logged in, you just render another template (loggedInHeader.scala.html in this case), else you call another method on a controller (but it can be on any type of class) :

app/controllers/Application.java :

class Application extends Controller {
  ...
  public static Html loginFormHeader() {
    Form form = Form.form(...);
    return views.html.loginFormHeader.render(form);
  }
}

This method construct the Form and render it using a template like this :

views/loginFormHeader.scala.html :

@(form: Form)
...

You can call the @controllers.Application.loginFormHeader() method from any template you want (event from a main layout template) and you don't need to build the Form object anywhere else.