Confusion regarding the use of @ in view classes of the Play framework

61 views Asked by At

I am mostly guessing how to use @ in Play. The following code compiles if I do not have a blank space between if and ( but not otherwise. Also, I had to use @ for if but not for else or the closing braces.

Questions:

  1. Shouldn't I use @ for all code written in Scala?

  2. What are the rules for using @ in a Play framework view?

This doesn't compile:

@if (userForm.value.isDefined) { 

This does:

@if(userForm.value.isDefined) {
          <h1>@userForm.get.name (userForm.get.age)</h1>
          <h2>Lives at @userForm.get.address.fullStreet</h2>
        **} else { //no @ required!**
            <h1>Feed User Data</h1>
            @helper.form(action=routes.Data.post){
            @helper.inputText(userForm("name"))
            <input type="submit" name="send" value="submit"/>
            } **//no @ required for closing braces!**
        }
1

There are 1 answers

0
Matthias A. Eckhart On

The special character @ in the template language is often referred to as the magic character or twirl (like the Play template engine). As the documentation states, it indicates the beginning of a dynamic statement.

Shouldn't I use @ for all code written in Scala?

No, just for the beginning of a dynamic statement. As you have already noticed, you don't need the magic character @ for an else block, as it is part of the if statement.

What are the rules for using @ in a Play framework view?

The only rule I can think of is that it is not necessary to explicitly close dynamic statements. Also, keep in mind to escape @ with @@, e.g. john@@doe.com.

Read more about Play's template engine and common use cases.