2
votes

Sorry for the stupid question, but I'm new to Scala and I'm learning Scala and Play Framework:

I have to implement a navbar in my main.scala.html template page, and I have to set the active class properly.

I'm using scala 2.12 and Play framework 2.7.2.

Which is the way to retrive the request object in order to pickup the current uri?

2

2 Answers

0
votes

Try passing the request as an implicit parameter to main template like so

@(name: String)(implicit request: RequestHeader)

Hello @name. You are at url:
@{request.host}@{request.uri}

Make sure the request is marked as implicit in the controller so that it gets automatically passed in to main template like so

class HomeController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {
  def index = Action { implicit request =>
    Ok(views.html.main("Picard"))
  }
}

Now hitting the route

GET / controllers.HomeController.index

should output

Hello Picard. You are at url:
localhost:9000/
0
votes

Thank you, i've retrieved the request.

Just to explain better: My project setting are the following: I have two controller HomeController, WidgetController, then i have four page main.scala.html (template) , home.scala.html, index.scala.html and listWidget.scala.html. Then my routes look like:



    GET   /    controllers.HomeController.home
    GET     /index                      controllers.WidgetController.index
    GET     /widgets                    controllers.WidgetController.listWidgets
    POST    /widgets                    controllers.WidgetController.createWidget

My main template it like this:

@(title: String)(content: Html)(implicit request: RequestHeader)

<!DOCTYPE html>
<html lang="en">
    <head>
        @* Here's where we render the page title `String`. *@
        <title>@title</title>
    </head>
    <body>
        <div class="container">
            @(request)
            @content
        </div>
    </body>
</html>

the home page looks like:

@(implicit request: RequestHeader)

@main("Welcome to Play") {
  <h1>Home</h1>
}(request)

the HomeController looks like :

@Singleton
class HomeController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {

  def home() = Action { implicit request: Request[AnyContent] =>
    Ok(views.html.home(request))
  }
}

so i have to pass the request in each page i make... it is a smarter way to get the request without modify each page?