Using Play Framework 2 I've noticed the rendered Scala HTML templates don't like indented @if
or @for
.
So, for example, something like that:
<ul>
@for(test <- tests) {
<li>@test.name</li>
}
</ul>
Will have extra unneeded spaces. To fix it, I need to do something like that:
<ul>
@for(test <- tests) {
<li>@test.name</li>
}
</ul>
Which will get messy with additional @defining
or other statements.
So, is there a way to prettify/beautify Scala templates rendering in order to get rid of extra white spaces?
UPDATE:
Reading this thread I've noticed extra spaces and line breaks are added as well because of the parameters on top of the templates. So this:
@(myParam: String)
<!DOCTYPE html>
<html>
<head></head>
<body></body>
</html>
will add 3 extra line breaks on top of the resulting HTML. Which is definitely annoying.
The thread seems to say there are no option at the moment to correct that.
So for more details I've used @biesor answer and went through these steps:
Add HtmlCompressor as a plugin
In Build.scala:
PrettyController
Then every controllers should extend
PrettyController
.I've released a Google HTML Compressor plugin for Play 2.1. You can find it on GitHub.
I was expecting answers which truly "prettify" the HTML output, in the sense of properly indenting the output in addition to removing blank lines. However,
HtmlCompressor
only compresses the output, and has no pretty printing logic.I came up with a solution that uses both
HtmlCompressor
for compression in production, and Jsoup for pretty-printing during development. I don't care about calling theprettify
conversion explicitly, so my solution looks like this:In dev mode this produces some nicely formatted HTML.
The required changes to
build.sbt
are:Echoing on bluenote10's answer I created the following, it does not require third party libraryDependecies. It would be nice to integrate it into a filter, unfortunately I am not sure how to do that correctly today.
Of course there is always some option :), trim the body and set header again so (cause after operations on the String it will be returned as
text/plain
):for 'beauty' loops or if's you need to write more compact code
And finally you can use some compressor (ie. com.googlecode.htmlcompressor) to... minify whole page (in this sample for production mode only)