Search code examples
playframeworkplayframework-2.0code-formattingscala-template

Is it possible to prettify scala templates using play framework 2?


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.


Solution

  • So for more details I've used @biesor answer and went through these steps:

    Add HtmlCompressor as a plugin

    In Build.scala:

    val appDependencies = Seq(
        "com.googlecode.htmlcompressor" % "htmlcompressor" % "1.5.2"
    )
    

    PrettyController

    public class PrettyController extends Controller {
    
        public static Results.Status ok(Content content) {
            return Results.ok(prettify(content)).as("text/html; charset=utf-8");        
        }
    
        public static Results.Status badRequest(Content content) {
            return Results.badRequest(prettify(content)).as("text/html; charset=utf-8");        
        }
    
        public static Results.Status notFound(Content content) {
            return Results.notFound(prettify(content)).as("text/html; charset=utf-8");      
        }
    
        public static Results.Status forbidden(Content content) {
            return Results.forbidden(prettify(content)).as("text/html; charset=utf-8");     
        }
    
        public static Results.Status internalServerError(Content content) {
            return Results.internalServerError(prettify(content)).as("text/html; charset=utf-8");       
        }
    
        public static Results.Status unauthorized(Content content) {
            return Results.unauthorized(prettify(content)).as("text/html; charset=utf-8");      
        }
    
        private static String prettify(Content content) {
            HtmlCompressor compressor = new HtmlCompressor();
            String output = content.body().trim();
    
            if (Play.isDev()) {
                compressor.setPreserveLineBreaks(true);
            }
    
            output = compressor.compress(output);
    
            return output;
        }
    }
    

    Then every controllers should extend PrettyController.