这足够了吗?
import scala.collection.mutable
import scala.util.matching.Regex.Groups
import scala.xml.XML
type Data = mutable.Map[Symbol, Any]
object Data {
def empty = mutable.Map.empty[Symbol, Any]
}
class Assignment(identifier: Symbol, data: Data) {
def :=(value: Any) {
data(identifier) = value
}
}
implicit def symbol2assignment(id: Symbol)(implicit data: Data) =
new Assignment(id, data)
def bind(template: String)(implicit data: Data) = {
val attributes = """=\{([^{}]+)}""".r
.replaceAllIn((_: String), _ match {
case Groups(identifier) =>
"=\"%s\"".format(data(Symbol(identifier)))
})
val rest = """\{([^{}]+)}""".r
.replaceAllIn((_: String), _ match {
case Groups(identifier) =>
data(Symbol(identifier)).toString
})
(attributes andThen rest andThen XML.loadString)(template)
}
implicit val data = Data.empty
'name := "bob"
'text := "hi there"
val bound = bind("<ex name={name}>{text}</ex>")
assert(bound == <ex name="bob">hi there</ex>)