casualjim
10/29/2010 - 10:34 AM

Template support trait for scalatra

Template support trait for scalatra

trait TemplateSupport extends ScalateSupport with Logging { self: (
    ScalatraKernel with FlashMapSupport with CookieSupport { def servletContext: ServletContext }) =>



  private var _viewsLocation = "/WEB-INF/views"
  val Ssp = "ssp"
  val Scaml = "scaml"
  val Jade = "jade"
  val Mustache = "mustache"

  protected def viewsLocation =
    if (_viewsLocation.endsWith("/")) _viewsLocation.substring(0, _viewsLocation.length - 1) else _viewsLocation

  protected def viewsLocation_=(location: String ) = {
    _viewsLocation = if (location.endsWith("/")) location.substring(0, location.length - 1) else location
    _viewsLocation
  }

  protected def templatePath(templateName: String, extension: String = "ssp") = {
    val ext = if (extension.startsWith(".")) extension else (".%s" format extension)
    val templ = if (templateName.startsWith("/")) templateName else ("/%s" format templateName)
    viewsLocation + templ + ext
  }

  protected def render(path: String, options: (String, Any)*) = {
    log debug "Rendering template with path [%s] and options: %s".format(path, options)
    response.setContentType("text/html")
    renderTemplate(path, (("flash" -> flash) :: options.toList):_*)
  }

  protected def ssp(templateName: String, options: (String, Any)*)  = {
    render(templatePath(templateName, Ssp), options:_*)
  }

  protected def scaml(templateName: String, options: (String, Any)*) = {
    render(templatePath(templateName, Scaml), options:_*)
  }

  protected def jade(templateName: String, options: (String, Any)*) = {
    render(templatePath(templateName, Jade), options:_*)
  }

  protected def mustache(templateName: String, options: (String, Any)*) = {
    render(templatePath(templateName, Mustache), options:_*)
  }


  override def createRenderContext: ServletRenderContext = {
    templateEngine.bindings =
            Binding("flash", "org.scalatra.FlashMap") ::
            Binding("params", "scala.collection.Map[String, String]") ::
            Binding("title", "String") ::
            Binding("cookies", "org.scalatra.SweetCookies") ::
            Binding("session", "org.scalatra.RichSession") :: templateEngine.bindings

    val context = new ServletRenderContext(templateEngine, request, response, servletContext)
    context.attributes.update("flash", flash)
    context.attributes.update("cookies", self.cookies)
    context.attributes.update("session", new RichSession(session))
    context.attributes.update("params", params)
    context.attributes.update("title", "")
    context
  }
}