A Scala Wrapper for Apache Velocity
Groovy has string interpolation in two forms: GStrings and Groovy Templates. Scala has -- nothing in that area, unless you count String concatenation or printf-like format strings. But the Java world has template engines, here is how to use one with additional comfort.
When a program has to generate text where most text is fixed and only some portions have to be dynamic, using templates is a natural approach. Groovy has GStrings and Groovy Templates, the Unix shells have "here documents", other scripting languages have different approaches to string interpolation.
The Scala library is still -- how shall I put it -- lean in that area and has no special support for text generation. But of course you can leverage Java libraries for that. So let's go and show the Groovy people that Scala has no problem generating some text!
I have used Apache Velocity with some success before, that's why I choose Velocity as the template engine. But I'd hate to have to create a resource file for each template in my program, even for those five-liners. Therefore I have put together a little wrapper library that prettifies using Velocity a little bit.
Here's some usage example to explain what it lets you do:
import eu.kneissl.scala.velocity.Conversions._
assert ("Hello ${yourname}. My name is ${myname}".merge('yourname->"Guest",
'myname->"Martin")
== "Hello Guest. My name is Martin"
assert ("#foreach( $i in $is )$i#end".merge('is->(1 to 3))
== "123")
case class Person (name: String)
val people = List(Person("Peter"), Person("Paul"), Person("Mary"))
val template: Template = "Hello ${yourname}. My name is ${myname}"
people foreach { person => println(template.merge('yourname->person.name, 'myname->"Martin") }
The Wrapper is described in a little more detail on its project page. Have fun!
_____tags:















