Reputation: 2518
I have several templates in my play/scala project. I want to get access to the currently logged in user in my main template. (so that I can put a Welcome 'username' text on the top of the page on all templates not only the "logged in pages")
I could put a parameter in my main template:
@(user: User)
But I have several templates that reference to the main template that doesn't have access to the logged in user. Pages like about, contact etc.
The only templates that have access to the logged in user is the "logged in" pages. Like user profile, user settings. From there, I can pass the logged in User object to the main template. But from the other pages I can't.
If I make the parameter "user" in main template as an optional parameter it will be problems anyway since I'm going to use the logged in users data on all pages if a user is logged in.
How could I solve this?
Please tell me if you need more input.
Upvotes: 0
Views: 1229
Reputation: 2468
You would need to use session to store id which you can use to identify the user, for example use user email as an id, from any action in controller retrieve user from db base on this id stored in session and pass 'username' as an Option to template, use option in case there is no logged in user, like this:
def about = Action { implicit request =>
val username:Option[String] = User.findUserName(request.session.get(userSession))
Ok(views.html.Applications.about(username)
}
example of about template, just pass username to main template
@(username:Option[String])
@main(username) {
// your content
}
example of main template display username if it is defined
@(username: Option[String])(content: Html)
@if(username.isDefined) {
<p> username.get</p>
}
Upvotes: 1
Reputation: 12101
If I understand you correctly, you need this:
Controller (Application.scala):
object Application extends Controller {
def index = Action {
val user = "smth" //assign your user name here
val parameter = "another parameter"
Ok(views.html.yourTemplate(user, parameter))
}
}
Template (yourTemplate.scala.html):
@(user: String, parameter: String)
<!--main template wrapping yourTemplate-->
@main("Welcome") {
<p>Hello, @user</p>
}
Upvotes: 1