Mustache templates in Scala

June 06, 2013

Quick start

Grab a version of the compiler:

wget -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"hello.mustache").getPath
val mustache = mf.compile(path)

val writer = new
val model  = Model(target = "world", numbers = List(1,2,3,4))

mustache.execute(writer, model)


// 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
    <p>Hello, world!</p>