开发者

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 % ["me@mail.com","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?


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("me@mail.com","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 % ("me@mail.com","Anderson")


You can just use a function for that:

val t = (s:String) => <someXML>{s}</someXML>

As opposed to format strings, this will give you the benefits of static typing. For example:

val ageXml = (age:Int) => <age>{age}</age>


The accepted answer is great for XML, but for other syntaxes I like Johannes Rudolph's scala-enhanced-strings plugin.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜