scalaplayframework-2.0twirl

Variable in Play Framework 2.x Template


I browsed the web, but did not find an answer anywhere. If I missed something, please point me to a tutorial.

So I want to define a variable in a Play Framework template and, of course, use it later on.

Currently my code looks like this:

@if(menuitems.fetchFromVerySlowDatabase() != null) {
<ul>
    @for(menuitem <- menuitems.fetchFromVerySlowDatabase()) {
        <li><a href="@menuitem.getUrl()">menuitem.getTitle()</a></li>
    }
</ul>
}

I know I can cache menuitems.fetchFromVerySlowDatabase but what I am really looking for is something like that:

@menuitems_from_database = menuitems.fetchFromVerySlowDatabase();
@if(menuitems_from_database != null) {
<ul>
    @for(menuitem <- menuitems_from_database) {
        <li><a href="@menuitem.getUrl()">menuitem.getTitle()</a></li>
    }
</ul>
}

Thank you!

I am using Java as programming language.

Best, schube


Solution

  • Just remember to do it in one line

    @import scala.Predef; var menuitems_from_database = menuitems.fetchFromVerySlowDatabase();
    

    An example of the live code (modification of the index.scala.html from the default template):

    @import scala.Predef; var menuitems_from_database = new java.util.ArrayList[String]()
    @(message: String)
    
    @{
      menuitems_from_database.add("1")
      menuitems_from_database.add("2")
      ""
    }
    
    @main("Welcome to Play") {
        @if(menuitems_from_database != null) {
                <ul>
                    @for(menuitem <- menuitems_from_database) {
                        <li><a href="@menuitem">@menuitem</a></li>
                    }
                </ul>
            }
    }
    

    Resulting HTML:

    <!DOCTYPE html>
    <html lang="en">
        <head>            
            <title>Welcome to Play</title>
            <link rel="stylesheet" media="screen" href="/assets/stylesheets/main.css">
            <link rel="shortcut icon" type="image/png" href="/assets/images/favicon.png">
            <script src="/assets/javascripts/hello.js" type="text/javascript"></script>
        </head>
        <body>
                <ul>
                        <li><a href="1">1</a></li>
                        <li><a href="2">2</a></li>
                </ul>
        </body>
    </html>