在 Ruby 中我可以这样:
string=<<EOTEMPLATE
<root>
<hello>
<to>%s</to>
<message>welcome mr %s</message>
</hello>
...
</root>
EOTEMPLATE
当我想“渲染”模板时,我会这样做:
rendered = string % ["me@mail.com","Anderson"]
它会用数组中传递的值填充模板。除了使用 Java 的 String.format
之外,在 Scala 中有没有办法做到这一点?如果我用 Scala 写这个:
val myStr = <root>
<hello>
<to>{address}</to>
<message>{message}</message>
</hello>
</root>
生成的 XML 将已经被“填充”。有什么方法可以“模板化”XML?
最佳答案
使用函数和 Scala 的 XML:
val tmpl = {(address: String, message: String) =>
<root>
<hello>
<to>{address}</to>
<message>{message}</message>
</hello>
</root>
}
和:
tmpl("me@mail.com","Anderson")
一些糖:
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")
关于xml - Scala 填充模板的方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5770550/