Declare variable in a Play2 scala template

Viewed 43357

How do you declare and initialize a variable to be used locally in a Play2 Scala template?

I have this:

@var title : String = "Home"

declared at the top of the template, but it gives me this error:

illegal start of simple expression """),_display_(Seq[Any](/*3.2*/var)),format.raw/*3.5*/(""" title : String = "Home"
9 Answers

In twirl templates I would recommend using the defining block, because the

@random = @{
     new Random().nextInt
}

<div id="@random"></div>
<div id="@random"></div>

would result in different values when used multiple times!

@defining(new Random().nextInt){ random =>
    <div id="@random"></div>
    <div id="@random"></div>
}

There is one obvious solution which looks quite clean and may be preferred sometimes: define a scope around the template, define your variable inside of it, and let the scope produce the html code you need, like this:

@{
  val title = "Home"

  <h1>Welcome on {title}</h1>
}

This has some drawbacks:

  • you are generating your html as Scala NodeSeq this way, which may be limiting sometimes
  • there is a performance issue with this solution: the code inside of @{ seems to be compiled runtime, because the Scala code generated for the page loooks like this (some usual Twirl stuff deleted):

The generated code:

...    

Seq[Any](format.raw/*1.1*/("""<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Basic Twirl</title>
    </head>
    <body>

        """),_display_(/*9.10*/{
            val title = "Home"

                <h1>Welcome on {title}</h1>
        }),format.raw/*15.10*/("""

    """),format.raw/*17.5*/("""</body>
</html>"""))
      }
    }
  }

...

For anyone who tries the answer of Govind Singh:
I had to put the import line with the variable under the parameter list, i.e.

@(title:String)(implicit session:play.api.mvc.Session)
@import java.math.BigInteger; var i=1; var k=1

works.

But putting the import with the variable over the import statement, i.e.

@import java.math.BigInteger; var i=1; var k=1
@(title:String)(implicit session:play.api.mvc.Session)

did not work for me and resulted in the error:

expected class or object definition
@isExcel= {@Boolean.valueOf(java.lang.System.getProperty(SettingsProperties.isExcel))}
Related