Skip to content

Instantly share code, notes, and snippets.

@seglo
Last active August 22, 2017 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seglo/eb223c0f87d8a7d02fec9b90a11b27e9 to your computer and use it in GitHub Desktop.
Save seglo/eb223c0f87d8a7d02fec9b90a11b27e9 to your computer and use it in GitHub Desktop.
package object controllers {
private def rel(url: String)(implicit request: Request[AnyContent]): String = {
val count = request.uri.count(c => c == '/')
(url, count) match {
/**
* Requested url is '/' and we are at the root of the app. Link to root route with '.'.
*/
case ("/", 1) => "."
/**
* Requested url is anything and we are the root of the app. Make link relative by stripping '/' prefix.
*/
case (_, 1) => url.stripPrefix("/")
/**
* All other url's are made relative by adding '..' for the depth between requested url and root of the app, -1.
*/
case _ => (1 until count).map(_ => "..").mkString("/") + url
}
}
implicit class RelativeCall(call: Call) {
def relative(implicit request: Request[AnyContent]): Call = call.copy(url = rel(call.url))
}
}
// Example calls to reverse router from view
// To a static asset:
<link rel="stylesheet" media="screen" href="@routes.Assets.versioned("bootstrap.css").relative">
// To a controller method:
<a href="@routes.Topic.topic(cluster,topic).relative" class="cancel-button btn btn-default" role="button">Cancel</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment