scalascalatescala-template

Scala Templates: Map a String to a Template


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

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


Solution

  • 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))