Dynamically generate label for checkbox in play framework

185 Views Asked by At

I am quite new to Scala and the play framework and have problems generating a label for a checkbox in a form. The label is generated using the play framework (2.6.10) and its twirl template engine. I am also using the play-bootstrap library.

The following is a simplified version of my 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")
    }
}

I am unable to "evaluate" the @repo.priceCar part. It is just not evaluated and I get the literal string "@repo.priceCar".

According to the play framework documentation regarding string interpolation, I should use $ instead of @, but that doesn't work either.

When I leave out the " around the string I get all sorts of errors.

I would appreciate a hint on what I have to do.

2

There are 2 best solutions below

0
On BEST ANSWER

Your issue is that the compiler is reading the String literally as Checkbox @repo.priceCar.

You will need to either add Strings together or use String interpolation to access this variable, as @ is not a valid escape character in normal Scala Strings:

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

This is injecting the variable repo.priceCar into the String, rather than just reading repo.priceCar literally as a String.

0
On

In general when you want to place a variable within a string you use $:

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

Now, if there is member like user.username you need to use ${user.username}:

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

So overall, you need to use the escape character @ within the Playframework's views, when you use the variable so it will be:

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

Therefore the '_text value should be as following:

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