2

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>
}

1 Answer 1

7

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>
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

That worked. The second curly brace was the problem. Also the space after the if and newline before else was giving errors in Eclipse. Thanks!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.