Rendering newline charactors from variable in Twirl

1k views Asked by At

I have a toy Play framework project. And my Java code is something like:

    String r = "apple\nbanana";
    return ok(index.render(r));

And my index.scala.html is something like

@(r: String)

<table border="1" style="width:98%">
<tbody>
  <tr>
    <td>@r</td>
  </tr>
</tbody>
</table>

The problem is that, in the displayed html, the newline character is gone. I want to get two lines in html but only get one line.

I even tried changing the line in Java to something like:

 String r = "apple<br>banana";

But the html still shows one line instead of two lines, It just shows

"apple<br>banana"

So how can I get two lines (making the newline character work) in Twirl?

1

There are 1 answers

0
Daniel Olszewski On BEST ANSWER

Be default, Twirl escapes all HTML tags from the dynamic content. If you want to render tags from a variable you can use @Html(). In your case it would be like this:

@(r: String)

<table border="1" style="width:98%">
<tbody>
  <tr>
    <td>@Html(r)</td>
  </tr>
</tbody>
</table>

Obviously the new line character doesn't work because browsers ignore white spaces while rendering HTML output.