Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play reverse routing without a Request instance

I'm using a template to generate an email in Play. That email includes an URL which is generated through reverse routing :

<a href="@routes.MyController.downloadFile(user).absoluteURL()">

The problem is, the downloadFile function takes an implicit request: Request parameter (as any Action) and I don't always have a Request when I'm sending an email (it can be triggered out of a request/response workflow).

Is there some way to obtain the reverse route anyway ? Or maybe should I pass it a dummy request object (and then, how to generate one ?)

like image 608
Weier Avatar asked Sep 24 '19 11:09

Weier


2 Answers

When implicit request is not available, you should use method described below defined in play.mvc.Call (play.api.mvc.Call returned by reverse router extends java play.mvc.Call class, so there is no additional work needed):

/**
 * Transform this call to an absolute URL.
 *
 * @param secure true if the absolute URL should use HTTPS protocol instead of HTTP
 * @param host the absolute URL's domain
 * @return the absolute URL string
 */
 public String absoluteURL(boolean secure, String host)

Example view code:

@(secure: Boolean, host: String)
<a href="@routes.MyController.downloadFile(user).absoluteURL(secure, host)">

secure and host values could be obtained from request or defined somewhere in application configuration.

like image 64
Pawel Hawro Avatar answered Nov 20 '22 12:11

Pawel Hawro


Try putting FakeRequest on the compile classpath

libraryDependencies += "org.scalatestplus.play" %% "scalatestplus-play" % "5.0.0"

and then provide it as a default request parameter to the template

@(foo: String)(implicit request: RequestHeader = play.api.test.FakeRequest())
like image 30
Mario Galic Avatar answered Nov 20 '22 12:11

Mario Galic