Mustache templates in Scala

June 06, 2013

Quick start

Grab a version of the mustache.java compiler:

wget http://search.maven.org/remotecontent?filepath=com/github/spullara/mustache/java/compiler/0.8.12/compiler-0.8.12-jar-with-dependencies.jar -O compiler-0.8.12-jar-with-dependencies.jar

Create a simple Mustache template:

echo 'Hello, {{target}}!' > hello.mustache

Fire up Scala and try it out:

$ scala -cp compiler-0.8.12-jar-with-dependencies.jar

scala> :paste
// Entering paste mode (ctrl-D to finish)

val mf = new com.github.mustachejava.DefaultMustacheFactory
mf.setObjectHandler(new com.twitter.mustache.ScalaObjectHandler)

val path = new java.io.File("hello.mustache").getPath
val mustache = mf.compile(path)

val writer = new java.io.PrintWriter(System.out)
val model  = Model(target = "world", numbers = List(1,2,3,4))

mustache.execute(writer, model)

writer.flush

// Exiting paste mode, now interpreting.

Hello, world!

Web application

A basic Servlet:

class MustacheServlet extends javax.servlet.http.HttpServlet {

  val mf = new com.github.mustachejava.DefaultMustacheFactory()
  mf.setObjectHandler(new com.twitter.mustache.ScalaObjectHandler)

  override def service(req: HttpServletRequest, res: HttpServletResponse) {
    val path = getClass.getClassLoader.getResource("hello.mustache").getFile
    val mustache = mf.compile(path)
    val model = Model(target = "world", numbers = List(1,2,3,4))
    mustache.execute(res.getWriter, model)
  }
}

Try it by cloning this project, launching sbt, and running the container:start command:

$ sbt

> container:start

Test it by pointing a Web browser at http://localhost:8080

$ curl localhost:8080
<html>
  <head>
    <title>Mustache</title>
  </head>
  <body>
    <p>Hello, world!</p>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
    </ul>
  </body>
</head>