12

I have a simple view (Play! template) that accepts an Html object. I know now that this object is play.twirl.api.Html (in Java). In the controller I want to render. return ok(layout.render("<h1> something </h1>")); I'm using Play! 2.3.x

But I fail to find a valid conversion from String to Html. I've tried casting and setting the String as the ctor argument for a new Html object but all failed. I have found no documentation on the twirl api.

Here is my question: How do I convert a String to Html in Play! (Java) without changing the template?

1 Answer 1

13

You have two possibilities (anyway in both you need to modify your template)

First is escaping HTML src within the view:

public static Result foo() {
    return ok(foo.render("<h1>Foo</h1>"));
}

View foo.scala.html:

@(myHeader: String)

@Html(myHeader)

Second is passing ready-to-use Html param:

import play.twirl.api.Html;

//....

public static Result bar() {
    return ok(bar.render(Html.apply("<h1>Bar</h1>")));
}

View bar.scala.html

@(myHeader: Html)

@myHeader
Sign up to request clarification or add additional context in comments.

2 Comments

May I ask you where you learned this? I always seem to fail to find this sort of stuff. Where is a reference (full) of the entire API? It's nowhere to be found and rather frustrating.
First approach (@Html(param)) comes from Play's docs, second from deducation (tip: IntelliJ with Play 2 support + downloaded sources helps a lot) ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.