Mule
Mule

Reputation: 878

Play Framework 2.x access variable in parent layout

Below is a simple main.scala.html template.

@import services.UserProvider
@(userProvider: UserProvider)

<!DOCTYPE html>
<html lang="@lang().code()">
    <head>
    </head>

    @defining(userProvider.getUser(session())) { user =>
    <body>
        <main id="main-container">
            <div class="content">
                @content
            </div>
        </main>
    </body>
    }
</html>

I have defined a user variable using @defining. In all of my child templates that inherit from main.scala.html, is there any way to access this "user" variable without having to make the same @defining(userProvider.getUser(session()))) call repeatedly (as shown in the child template below)?

@import services.UserProvider
@(userProvider: UserProvider, model: MyModel)

@main(userProvider, model) {

    @defining(userProvider.getUser(session())) { user =>

        <div class="block-content">
            @views.html.foo.list._filter(user, model)
        </div>

        <div>
            @_showingBarPartial(user, model)
            @views.html.foo.list._table(model, user)
        </div>
    }

}

I have this code snippet all over my project and I am trying to determine if this is necessary and/or if it could lead to problems. It seems like, I have already defined it once in the main (parent) template, why not just reuse it instead of having to reget it in child templates.

Thanks for any suggestions.

Upvotes: 0

Views: 189

Answers (1)

tgk
tgk

Reputation: 4116

Could you consider using a scala implicit?

from you controller you could define

implicit val user: User = userProvider.getUser(session())

and then in each template you would reference the implicit from the parent closure, the trick is that you have to pass reference to the implicit through each template:

main.scala.html

@(model: MyModel)(implicit val user: User)

@main(userProvider, model) {
  <div class="block-content">
    @views.html.foo(model)
    ...

foo.scala.html

@(model: MyModel)(implicit val user: User)

  @user.name is logged in  @* <--- using the implicit in a child template *@

Upvotes: 1

Related Questions