3

Hi So I have a while loop:

@for(i <- 0 until consoles.size) {
    ... Do something
    ... Add records to a column
}

But what I would like to add a variable and depending on what is going on add it to a different group. For example:

@var column = 0;
@for(i <- 0 until consoles.size) {
        @if(consoles[i].groupname != consoles[i - 1].groupname) {
             column = column + 1;
        }
        ... Do something
        ... Add records to a column
    }

Is this possible. The only thing I have found is by passing in a variable and using that but I would prefer not to do that, although it will only be an int so not sending alot more information to the client I would prefer if I could just declare in the scala template?

Any help would be appreciated.

1
  • 1
    +1, just hitting this issue now. Having to wrap great swaths of code with @defining is annoying, but not being able to use a mutable var is a major PITA, particularly when dealing with nested loops. How do I stop iterating through an inner loop when I have no state counter to work with? Commented Oct 22, 2012 at 21:10

2 Answers 2

6

In your case there are better solutions. Since templates are in scala, you can use some great methods from Collections' API, such as groupBy :

@myList.groupBy(_.groupname).map {
    case (group, items) => {
        <h2>@group</h2>
        @items.map { item =>
            ...
        }
    }
}

Scala templates doesn't require Scala skills, but you need at least to understand the lists API, it's a true life saver !

Sign up to request clarification or add additional context in comments.

Comments

3

In play templates you can't define var. Furthermore, in Scala you are encouraged to use immutable objects rather than mutable ones.

You have two alternatives to do what you want:

  1. Use a more scala idiomatic way as @Maxime answered
  2. Deal with vals

In addition to @Maxime's answer, you can create new vals in your template using defining

From play 2 documentation :

@defining(user.firstName + " " + user.lastName) { fullName =>
    <div>Hello @fullName</div>
}

4 Comments

That won't make fullname a var.
True. You can't define a var in play2 templates. You have to : a) define vals b) use a more functional way as @Maxime answered. My answer was dealing with a) but wasn't that clear.
Thanks for that if I use @defining does this declare a string? or can I use this object as an int?
The function prorotype is def defining[T](t: T)(handler: T => Any), you can use any type.

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.