11
votes

I'm new at using Play Framework 2.0 (I am using Scala) and have a question about sessions.

I come from a Ruby on Rails background, so I tend to think of everything that I learn in Play Framework with respect to Ruby on Rails.

With that in mind, is there any way for me to call stuff stored in the Session while I am in the view?

If I have "hello" -> "world" stored in the Session, I want to be able to do something like @session.get("hello") and be able to use "world" in the view. Is this possible?

The other option I see is to store the value in a variable in the controller, and pass that along to the view by doing something like OK( var ), but that way seems kind of clunky especially if I start using more variables.

Thanks!

3

3 Answers

22
votes

Sessions in Play store in cookies and are really just for cross-request data. If that is what you want then you can use @session.get("hello") but what you might actually be after is a way to pass stuff from controllers to templates without having to specify them as parameters. In that case, see the very detailed answer to that question here: https://stackoverflow.com/a/9632085/77409

11
votes

Yes you can use @session.get("hello") in template, however it looks that you need to specify at least implicit parameter named 'session' at the beginning of the template when using templates with Scala controllers:

@()(implicit session: play.api.mvc.Session) 

Also there is flash scope - it differs from session that it lives only for one request and is not signed. So it is most often used just for transporting error/inf messages.

See Session and flash scopes doc

Finally as each template is just a Scala function, you can also call some action from your controller and retrieve session data

-3
votes

You can definetly call ur session in play templates.

Try this code - it works in views:

$session.session_variable_name;