Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top