Search code examples
templatesplayframeworkplayframework-2.0reusability

Reusable Scala code for all views in Play


I know I can declare a reusable pure Scala block like this in a template:

@title(text: String) = @{
  text.split(' ').map(_.capitalize).mkString(" ")
}

I can now call @title("someString") in the template but this code block is not accessible from outside this template.

How can I declare such a block that is accessible from other templates as well?

I've tried to create a new template title.scala.html like this:

@(text : String)
@{
    text.split(' ').map(_.capitalize).mkString(" ")
}

I can now call @title("someString") from any template I want, but this doesn't give me the exact same result as the first block, inside the template (I assume in the first case it returns a String whereas it returns Html in the second case).

I'm using Play framework 2.0.4 and I'm coding in Java (hence my limited Scala knowledge).


Solution

  • Using tags is targeted for building reusable blocks of HTML code, therefore it returns Html

    To work easily with common types of data you can easily add a custom Java class (for an example in freshly created utils package (in app directory), and prepare in it all required formatters as a static methods:

    utils.MyFormats.java:

    package utils;
    
    import org.apache.commons.lang3.text.WordUtils;
    
    public class MyFormats {
    
        public static String capitalize(String str) {
            return WordUtils.capitalize(str);
        }
    
        public static int sumElements(int a, int b) {
            return a + b;
        }
    
    }
    

    In template:

    <h2>Capitalized each word: @(utils.MyFormats.capitalize("foo bar"))</h2>
    <h3>Sum of two integers, 2+3 = @(utils.MyFormats.sumElements(2, 3))</h3>