“value getOrElse is not a member of String” in template

我的梦境 提交于 2019-12-11 11:21:51

问题


I have the following template code:

views/Login.scala.html:

@(loginForm: Form[views.Data])

@import mytemplates.loginform

@Main("") {
    email:@loginform(loginForm("email"))
    @*email:@loginForm("email").value.getOrElse("xyz")*@
}

views/mytemplates/loginform.scala.html:

@(emailField: Field)

@emailField.value.getOrElse("xyz")

views/Main.scala.html:

@(page: String)(content: Html)

<!DOCTYPE html>

<html>
    <body>
    @content
</html>

views/Data.java:

package views;

import play.data.validation.ValidationError;
import java.util.List;

public class Data {

    public String email = "";

    public Data() { }

    public List<ValidationError> validate() {

        return null;
    }
}

Compiling the above is successful. But if line @*email:@loginForm("email").value.getOrElse("xyz")*@ in Login.scala.html is uncommented compiling produces an value getOrElse is not a member of String error.

Why does this happen? I'd like to exclude the template mytemplates.loginform but can't get it to work.

edit: Following estmatic's advice I get the following:

views/Login.scala.html:

@loginForm("email").getClass: class play.data.Form$Field

@loginForm("email").valueOr("").getClass: class java.lang.String

views/mytemplates/loginform.scala.html:

@emailField.getClass: class play.core.j.PlayMagicForJava$$anon$1

@emailField.value.getClass: class scala.None$

I had to use valueOr("") in Login.scala.html otherwise a NullPointer execution exception would be produced. Clearly they are all different classes. I haven't used Play framework much and am not sure what this means.


回答1:


Since it looks like you have a Java project, the framework is going to do some automatic conversions here and there between the Java classes and their Scala equivalent.

Try this out:

@loginForm("email").getClass()
@loginForm("email").value.getClass()

Make this change on both Login.scala.html and loginform.scala.html and you'll see that you are dealing with different classes in each scenario.

When you go through the loginform template your field.value will be wrapped in a scala.Some object, which is why .getOrElse compiles in that case. When you do it directly in the main view you never leave Java-class-world, so your field.value is returned directly as a String.

If you are using the latest version of Play then you should be able to use the Field.valueOr method instead of getOrElse.

@loginForm("email").valueOr("xyz")


来源:https://stackoverflow.com/questions/22391677/value-getorelse-is-not-a-member-of-string-in-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!