Search code examples
javatemplatesplayframework-2.0playframework-2.3twirl

Undesirable syntax in Play framework templates


I am using Play 2.3.7 Java, and I am trying to render templates. I can get it to work, but only by using really ugly syntax. What I have that works so far is right here: https://gist.github.com/aaron235/c21866dd7bff0ba3fc0c

Clearly, having a bunch of curly-bracketed blocks of HTML isn't the best way to do this. My ideal 'home.scala.html' would look something like this: https://gist.github.com/aaron235/4f446dfa41feb7d02458

I'd like to have named parameters that parse into 'main.scala.html', but I can't find any resources that make sense, after thorough searching of SO, attempting to find information in "Play for Java" by Nicolas Leroux and Sietse de Kaper, and scouring the rest of the internet. Any help is appreciated.


Solution

  • In the template use cases documentation you can find a section devoted to your problem at the end of the Layout paragraph. Two different ways of declaring page-specific content blocks can be found there.

    By applying information from docs your view is going to look like this:

    @()
    
    @title = {
    <title>Welcome to MessageWorks.</title>
    },
    
    @stylesheets = {
    <link type="text/css" rel="stylesheet" href="/styles/main.css" />
    ...
    },
    
    @javascripts = {
    <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
    ...
    },
    
    @page = {
    <h1>MessageWorks</h1>
    ...
    } 
    
    @main(title)(stylesheets)(javascripts)(page)
    

    You have to define each section as a reusable block and than simply pass them to the main template as parameters.