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:<
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 the prettify
conversion explicitly, so my solution looks like this:
// required extra imports
import play.twirl.api.Html
import com.googlecode.htmlcompressor.compressor.HtmlCompressor
import org.jsoup.Jsoup
import org.jsoup.parser.Parser
@Singleton
class MyController @Inject() (environment: Environment) extends Controller {
/** Helper to format Html */
def prettify(content: Html): Html = {
val rawString = content.body.trim()
val html = environment.mode match {
case Mode.Dev =>
val doc = Jsoup.parse(rawString, "", Parser.xmlParser())
doc.outputSettings().indentAmount(2)
Html(doc.toString())
case _ =>
val compressor = new HtmlCompressor()
compressor.setPreserveLineBreaks(true)
Html(compressor.compress(rawString))
}
html
}
/** example usage */
def index = Action {
Ok(prettify(views.html.index))
}
}
In dev mode this produces some nicely formatted HTML.
The required changes to build.sbt
are:
libraryDependencies += "org.jsoup" % "jsoup" % "1.10.2"
libraryDependencies += "com.googlecode.htmlcompressor" % "htmlcompressor" % "1.5.2"