Search code examples
scalascalatescala-template

Scala Templates: Map a String to a Template


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


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