Permalink
Browse files

type-safe RenderContext construction

  • Loading branch information...
chrislewis committed Jan 3, 2011
1 parent dc72adb commit 63e1951fe7c58f804e9aa55f4d70cc00135508cb
Showing with 28 additions and 16 deletions.
  1. +28 −16 scalate/src/main/scala/scalate.scala
@@ -1,36 +1,48 @@
package unfiltered.scalate
import org.fusesource.scalate.{TemplateEngine, Binding}
import org.fusesource.scalate.{TemplateEngine, Binding, DefaultRenderContext, RenderContext}
import unfiltered.response.{HttpResponse, Responder}
import unfiltered.request.HttpRequest
/**
* private object that holds the default engine
*/
private[scalate] object ScalateDefaults{
val defaultTemplateDirs = List(new java.io.File("src/main/resources/templates"))
implicit val engine = new TemplateEngine(defaultTemplateDirs)
implicit def renderContext[A, B](req: HttpRequest[A], res: HttpResponse[B], engine: TemplateEngine) =
new DefaultRenderContext(req.requestURI, engine, res.getWriter)
}
import unfiltered.response.ResponseWriter
import unfiltered.request.HttpRequest
object Scalate {
/* An arity-3 function that constructs an appropriate RenderContext. */
type RenderContextBuilder[A, B] = (HttpRequest[A], HttpResponse[B], TemplateEngine) => RenderContext
}
/**
* This class will render the given template with the given attributes.
* An implicit Engine and Bindings can be passed to the constructor via
* its alternate parameters set. This is described further in demo-scalate
*/
case class Scalate(request: HttpRequest[_], template: String, attributes:(String,Any)*)
case class Scalate[A, B](request: HttpRequest[A], template: String, attributes:(String,Any)*)
(
implicit engine: TemplateEngine = ScalateDefaults.engine,
implicit engine: TemplateEngine = ScalateDefaults.engine,
contextBuilder: Scalate.RenderContextBuilder[A, B] = ScalateDefaults.renderContext _,
bindings: List[Binding] = List[Binding](),
additionalAttributes: List[(String, Any)] = List[(String, Any)]()
) extends ResponseWriter{
import java.io.PrintWriter
def write(writer: PrintWriter): Unit = {
import org.fusesource.scalate.DefaultRenderContext
val scalateTemplate = engine.load(template, bindings)
val context = new DefaultRenderContext(request.requestURI, engine, writer)
for(attr <- additionalAttributes) context.attributes(attr._1) = attr._2
for(attr <- attributes) context.attributes(attr._1) = attr._2
scalateTemplate.render(context)
) extends Responder[B]{
def respond(res: HttpResponse[B]) {
val writer = res.getWriter()
try {
val scalateTemplate = engine.load(template, bindings)
val context = contextBuilder(request, res, engine)
for(attr <- additionalAttributes) context.attributes(attr._1) = attr._2
for(attr <- attributes) context.attributes(attr._1) = attr._2
scalateTemplate.render(context)
}
finally { writer.close() }
}
}

0 comments on commit 63e1951

Please sign in to comment.