"Peter") Result: Hello Peter Is there a wa" /> "Peter") Result: Hello Peter Is there a wa" /> "Peter") Result: Hello Peter Is there a wa"/>

Scala Templates: Map a String to a Template

256 Views Asked by At

I use Scalate for templating. Usually it goes this way:

  • Template:

    Hello {{name}}

  • Parameters:

    `Map("name" -> "Peter")

  • Result:

    Hello Peter

Is there a way to get the Parameter Map as Result?

  • Template:

    Hello {{name}}

  • Request:

    Hello Peter

  • Result:

    Map("name" -> "Peter")

1

There are 1 best solutions below

2
Krzysztof Atłasik On BEST ANSWER

Maybe you're looking for regex with named groups?

//Regex with named groups
val pattern = """^Hello (?<firstname>\w+) (?<lastname>\w+)$""".r

val groups = List(
    "firstname",
    "lastname"
)

def matchAll(str: String): Option[Map[String, String]] = pattern
    .findFirstMatchIn(str)
    .map { matched =>
      groups.map(name => name -> matched.group(name)).toMap
    }

matchAll("Hello Joe Doe") //Some(Map(firstname -> Joe, lastname -> Doe))