Cristian Boariu
Cristian Boariu

Reputation: 9621

Why I cannot read my custom header in scala view?

In my Play 2 app, in a method from controller I add a new header like:

def index(id: Option[Long]) = SecuredAction { implicit request =>
....
Ok(views.html.platform.alerts.index(request.user, currentUserAlerts, 
   TweetsDAO.loadTweets(alertId, None, 15)))
        .withHeaders("isAdmin" -> userSettings.get.isAdmin.toString)
}

and I want to access the header in alerts.index scala view like:

@request.headers.get("isAdmin")

where request is defined as implicit in my view:

(implicit request: RequestHeader)

but nothing is shown.

If I print all headers in scala view, isAdmin is not there.

Does anybody know what I am doing wrong?

Upvotes: 0

Views: 146

Answers (1)

Michael Zajac
Michael Zajac

Reputation: 55569

Ok.withHeaders(...) adds headers to the Result returned to the user, not the RequestHeader, and is thus not passed to the view.

I don't see the point in trying to modify the RequestHeader when trying to pass some flag such as isAdmin to the view. Why not just add an explicit isAdmin: Boolean parameter to the view and pass it? That way you'd have to explicitly determine whether the user is an administrator, rather than relying on a header being added to the request, which can easily be overlooked.

Upvotes: 2

Related Questions