6

I need to print some raw HTML in Scala template using newest Play Framework 2.1.1 Messages, variables, simple for loops etc. everything is working fine. But what if I need to to do some logic and print out raw HTML into template?

@{
    val courts = venue.getCourts()
    val totalWidth : Int = 920
    .. some other initialization variables/values

    var output : String = ""
    for(court <- courts) {
        output += "<p>SomeComplexString</p>"
    }

    output
}

In this case @{} function returns output but that HTML is escaped and also it's not so practical (combining everything into single output variable before returning).

If I put something like

for(court <- courts) {
    println("<p>SomeComplexString</p>")
}

it's not working (I don't get any compile errors but there is nothing on output).

I could do

@for(court <- courts) {
    <p>SomeComplexString</p>
}

but then courts would be out-of-scope (let just say I can't define courts as template variable on the beginning).

What is the solution?

svenkapudija
  • 5,128
  • 14
  • 68
  • 96

1 Answers1

15

But what if I need to to do some logic and print out raw HTML into template?

Play Framework, like others MVC frameworks, recommends a strict separation of concerns. Your logic must be in your controller, not in the view. It's why it's relatively complicated to do that in the scala templates.

Furthermore, you can use @Html() to display unescaped variables.

Julien Lafont
  • 7,869
  • 2
  • 32
  • 52
  • correct answer but avoid using `@Html()` because of security concerns. – adis Apr 19 '13 at 10:57
  • @adis Can you please specify the security concerns of @Html()? – user1943442 Apr 12 '17 at 18:02
  • @user1943442 script injection if you just use `@Html` out of a user input. Read some more: http://wonko.com/post/html-escaping – adis Apr 13 '17 at 13:14
  • 1
    @adis Ah I thought there was something I was missing. I think avoiding the use of @Html() is bad advice. It's a necessary function. The better advice would be be aware of it's implications when applied to user-input. – user1943442 Apr 14 '17 at 13:49
  • @user1943442 Totally agree with your arguments! – adis Apr 20 '17 at 10:45