【问题标题】:Dynamically generate label for checkbox in play framework在播放框架中为复选框动态生成标签
【发布时间】:2018-08-07 00:17:35
【问题描述】:

我对 Scala 和 play 框架还很陌生,并且在为表单中的复选框生成标签时遇到了问题。标签是使用 play framework (2.6.10) 及其 twirl 模板引擎生成的。我也在使用play-bootstrap 库。

以下是我的form.scala.html的简化版。

@(enrolForm: Form[EnrolData], repo: RegistrationRepository)(implicit request: MessagesRequestHeader)

@main("Enrol") {
    @b4.horizontal.formCSRF(action = routes.EnrolController.enrolPost(), "col-md-2", "col-md-10") { implicit vfc =>
        @b4.checkbox(enrolForm("car")("hasCar"), '_text -> "Checkbox @repo.priceCar")
    }
}

我无法“评估”@repo.priceCar 部分。它只是没有被评估,我得到了文字字符串“@repo.priceCar”。

根据the play framework documentation regarding string interpolation,我应该使用$ 而不是@,但这也不起作用。

当我在字符串周围省略" 时,会出现各种错误。

我希望能得到有关我必须做什么的提示。

【问题讨论】:

  • 我没有测试过这个,但是你有没有试过像s"Checkbox ${repo.priceCar}"这样的东西?
  • @JamesWhiteley 是的,它正在工作。非常感谢!
  • 别担心!我会写一个答案,以便其他人遇到相同问题时可以找到解决方案。

标签: scala playframework twirl play-bootstrap


【解决方案1】:

您的问题是编译器将字符串按字面意思读取为Checkbox @repo.priceCar

您需要将字符串添加在一起或使用字符串插值来访问此变量,因为@ 在普通 Scala 字符串中不是有效的转义字符:

@b4.checkbox(enrolForm("car")("hasCar"), '_text -> s"Checkbox ${repo.priceCar}")

这是将变量repo.priceCar 注入到字符串中,而不是仅仅将repo.priceCar 读取为字符串。

【讨论】:

    【解决方案2】:

    一般来说,当你想在一个字符串中放置一个变量时,你使用$

    var something = "hello" 
    println(s"$something, world!") 
    

    现在,如果有user.username这样的会员,你需要使用${user.username}

    println(s" current user is ${user.username}")
    

    因此,总的来说,您需要在 Playframework 的视图中使用转义字符 @,当您使用变量时,它将是:

    s" Current user: ${@user.username}"
    

    因此'_text 的值应如下:

    '_text -> s"Checkbox ${repo.priceCar}" //we drop the @ because the line started with '@'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-28
      相关资源
      最近更新 更多