简体   繁体   English

Scala模板:将字符串映射到模板

[英]Scala Templates: Map a String to a Template

I use Scalate for templating. 我使用Scalate进行模板制作。 Usually it goes this way: 通常情况是这样的:

  • Template: 模板:

    Hello {{name}}

  • Parameters: 参数:

    `Map("name" -> "Peter") `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")

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM