Kevin Colin
Kevin Colin

Reputation: 357

How to serve a Play! scala template without routing through controller?

I want to have something like

Routes

GET   /endpoint   pathToTemplate.templateName.scala.html

In order to avoid the need to create a controller just to serve this template.

I need a template because I am serving up values using an imported scala library so this can't just be static html

@import tool.values._

<p>
  @Tool.getValue()
<p>

Upvotes: 1

Views: 495

Answers (1)

Daniel Olszewski
Daniel Olszewski

Reputation: 14411

It is impossible to achieve your desire solution but you can to make a workaround with one controller and the dynamic URL parts mapping.

Firstly create a controller which serves a view for any provided path. Route definitions must be placed in code for example with usage of a simple hash map instead of the route file.

object GlobalController extends Controller {

  private val getRouterMap = Map(
    "view1" -> views.html.view1(),
    "view2" -> views.html.view2(),
    "sub/view3" -> views.html.view3()
  )

  def route(path: String) = Action { implicit request =>
    Ok(getRouterMap.getOrElse(path, views.html.notFound()))
  }

}

Secondly at the end of the route file define a mapping for the created action as follow.

GET         /*path               controllers.GlobalController.route(path)

It is very important to put it as the last line. Otherwise it will shadow all other mappings defined below.

Hint

Anyway if I ware you I would reconsider your design. Singleton objects aren't easily testable. Sooner or later they will make your life really painful.

Upvotes: 3

Related Questions