Print HTML in Scala template
Asked Answered
I

1

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?

Iodism answered 18/4, 2013 at 20:2 Comment(0)
O
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.

Orangutan answered 18/4, 2013 at 20:50 Comment(5)
correct answer but avoid using @Html() because of security concerns.Outdate
@Outdate Can you please specify the security concerns of @Html()?Padlock
@Padlock script injection if you just use @Html out of a user input. Read some more: wonko.com/post/html-escapingOutdate
@Outdate 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.Padlock
@Padlock Totally agree with your arguments!Outdate

© 2022 - 2024 — McMap. All rights reserved.