在没有 Request 实例的情况下播放反向路由
Play reverse routing without a Request instance
我正在使用模板在 Play 中生成电子邮件。该电子邮件包含通过 reverse routing 生成的 URL :
<a href="@routes.MyController.downloadFile(user).absoluteURL()">
问题是,downloadFile
函数有一个 implicit request: Request
参数(和任何 Action
一样),而我并不总是有一个 Request
发送电子邮件(可以从 request/response 工作流程中触发)。
有什么方法可以获取反向路由吗?或者我应该给它传递一个虚拟请求对象(然后,如何生成一个?)
尝试将 FakeRequest
放入编译类路径
libraryDependencies += "org.scalatestplus.play" %% "scalatestplus-play" % "5.0.0"
然后将其作为默认 request
参数提供给模板
@(foo: String)(implicit request: RequestHeader = play.api.test.FakeRequest())
当隐式请求不可用时,您应该使用下面描述的方法定义在play.mvc.Call
中(play.api.mvc.Call
由reverse router extends java play.mvc.Call
class, 所以不需要额外的工作):
/**
* 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)
示例查看代码:
@(secure: Boolean, host: String)
<a href="@routes.MyController.downloadFile(user).absoluteURL(secure, host)">
secure
和 host
值可以从请求中获取或在应用程序配置的某处定义。
我正在使用模板在 Play 中生成电子邮件。该电子邮件包含通过 reverse routing 生成的 URL :
<a href="@routes.MyController.downloadFile(user).absoluteURL()">
问题是,downloadFile
函数有一个 implicit request: Request
参数(和任何 Action
一样),而我并不总是有一个 Request
发送电子邮件(可以从 request/response 工作流程中触发)。
有什么方法可以获取反向路由吗?或者我应该给它传递一个虚拟请求对象(然后,如何生成一个?)
尝试将 FakeRequest
放入编译类路径
libraryDependencies += "org.scalatestplus.play" %% "scalatestplus-play" % "5.0.0"
然后将其作为默认 request
参数提供给模板
@(foo: String)(implicit request: RequestHeader = play.api.test.FakeRequest())
当隐式请求不可用时,您应该使用下面描述的方法定义在play.mvc.Call
中(play.api.mvc.Call
由reverse router extends java play.mvc.Call
class, 所以不需要额外的工作):
/**
* 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)
示例查看代码:
@(secure: Boolean, host: String)
<a href="@routes.MyController.downloadFile(user).absoluteURL(secure, host)">
secure
和 host
值可以从请求中获取或在应用程序配置的某处定义。