Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala way of filling a template?

In Ruby I could have this:

string=<<EOTEMPLATE
<root>
  <hello>
     <to>%s</to>
     <message>welcome mr %s</message>
  </hello>
  ...
</root>
EOTEMPLATE

And when I want to "render" the template, I would do this:

rendered = string % ["[email protected]","Anderson"]

And it would fill the template with the values passed in the array. Is there a way to do this in Scala, other than using Java's String.format? If I write this in Scala:

val myStr = <root>
<hello>
<to>{address}</to>
<message>{message}</message>
</hello>
</root>

the resulting XML would already be "filled". Is there a way I could "templatize" the XML?

like image 468
Geo Avatar asked Apr 24 '11 12:04

Geo


1 Answers

Using a function and Scala's XML:

 val tmpl = {(address: String, message: String) =>
  <root>
    <hello>
      <to>{address}</to>
      <message>{message}</message>
    </hello>
  </root>
  }

and:

tmpl("[email protected]","Anderson")

Some sugar:

def tmpl(f: Product => Elem) = new {
   def %(args: Product) = f(args)
}

val t = tmpl{case (address, message) => 
  <root>
    <hello>
      <to>{address}</to>
      <message>{message}</message>
    </hello>
  </root>
}

t % ("[email protected]","Anderson")
like image 130
IttayD Avatar answered Sep 28 '22 23:09

IttayD