Question

I am a Java developer who recently started to learn about the Play Framework. I have been trying to get the below template working but cant seem to get it. I have got the following in my Scala template

@navItem(label: String, link1: String) = {
    @{if (Application.isAuthenticated()) {
    <li class="active">
        <a href="@link1">label</a>
    </li>
    }
    else {
    <li class="disabled">
        <a href="@link1">{label}</a>
    </li>
    }
    }
}

I am calling this later in my template like so

<ul class="nav">
@navItem("Search Documents", "/search")
</ul>

The generated link has href as localhost:9000/@link1 instead of localhost:9000/search. I am not sure whats going on.

PS: If I change my template as below it works fine. But I want to understand why the above template wont work.

@navItem(label: String, link1: String) = {
    <li class="@(if (Application.isAuthenticated()) "active" else "disabled")">
        <a href="@link">@label</a>
    </li>
}
Was it helpful?

Solution

Not quite sure about this, but my guess would be the following: The @{ ... } indicates the beginning of a dynamic statement and all of its content is treated as Scala code. Thus, it is a normal if-condition with two strings as a result, both of which are simply returned in the template.

Why are you marking it as a multi-line code block anyway? Have you tried it like this? (note the missing curly braces after the 2nd @ sign):

@navItem(label: String, link1: String) = {
  @if(Application.isAuthenticated()) {
    <li class="active">
      <a href="@link1">@label</a>
    </li>
  } else {
    <li class="disabled">
      <a href="@link1">@label</a>
    </li>
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top